SQL Server用逗号分隔

时间:2012-01-28 08:45:55

标签: sql-server split

我有一个关于在T-SQL中拆分列值的问题。 我有

Address_col

Nevada,USA
Tokyo,Japan
Hanoi,Vietnam

我想用逗号分隔值到

Address_col     Country

Navada          USA
Tokyo           Japan
Hanoi           Vietnam

我该怎么做?

2 个答案:

答案 0 :(得分:5)

declare @T table (Address_col varchar(20))

insert into @T values
('Nevada,USA'),
('Tokyo,Japan'),
('Hanoi,Vietnam')

select left(Address_col, charindex(',', Address_col)-1) as Address_col,
       stuff(Address_col, 1, charindex(',', Address_col), '') as Country
from @T

<强>更新
拆分三个部分的字符串可能如下所示: 声明@T表(Address_col varchar(20))

insert into @T values
('Nevada,USA,World'),
('Tokyo,Japan,World'),
('Hanoi,Vietnam,World')

select parsename(C, 3),
       parsename(C, 2),
       parsename(C, 1) 
from @T
  cross apply (select replace(Address_col, ',', '.')) as T(C)

答案 1 :(得分:1)

如果你只有两个部分,那么这是我能想到的最简单的部分。

选择SUBSTRING(Address_col,1,CHARINDEX(',',Address_col)-1)作为Address_col,         SUBSTRING(Address_col,CHARINDEX(',',Address_col)+ 1,LEN(Address_col))为国家