如何在SQL Server中将一列拆分为两列?

时间:2017-07-03 09:47:57

标签: sql-server

所以,我是SQL新手。我想把一个专栏分成两部分。值由冒号(:)分隔。我用了,

Select Left([Cost Center1], Charindex(':', [Cost Center1])-1) as [Cost Center]
       ,Substring([Cost Center1], Charindex(':', [Cost Center1])+1,
                  len([Cost Center1])-Len(Charindex(':', [Cost Center1]))
                  ) as [Project]
from Analytics.dbo.[Parent Table];

但上面的问题是它只提供了视图。我想更新我的桌子。怎么做? TIA。

1 个答案:

答案 0 :(得分:0)

您可以再添加2列

ALTER Table Analytics.dbo.[Parent Table]
ADD NewColumn1 varchar(100)

ALTER Table Analytics.dbo.[Parent Table]
ADD NewColumn2 varchar(100)

并更新其值

Update  Analytics.dbo.[Parent Table]
SET NewColumn1 = Left([Cost Center1], Charindex(':', [Cost Center1])-1),
    NewColumn2 = Substring([Cost Center1], Charindex(':', [Cost Center1])+1,
                  len([Cost Center1])-Len(Charindex(':', [Cost Center1]))

或者您可以添加2 coumputed column

ALTER Table Analytics.dbo.[Parent Table]
ADD NewColumn1 AS Left([Cost Center1], Charindex(':', [Cost Center1])-1)

ALTER Table Analytics.dbo.[Parent Table]
ADD NewColumn2 as Substring([Cost Center1], Charindex(':', [Cost Center1])+1,
                  len([Cost Center1])-Len(Charindex(':', [Cost Center1]))