如何将逗号分隔值拆分为列

时间:2017-04-12 08:12:33

标签: sql-server

来源表:

Value |name

1     |clar,alwin,antony,rinu,dami,prince

预期产出:

Value |  name1 |  name2 |  name3 | name4 |  name5 |  name6
1     | clar   | alwin  | antony | rinu  | dami   | prince

尝试了这个问题:

 Select Substring(name, 1,Charindex(',', name1) as name1,
 Substring(name,1, Charindex(',', name)+1, LEN(name)) as  name2,
 Substring(name, Charindex(',', name)+2, LEN(name)) as  name3,
 Substring(name, Charindex(',', name)+3, LEN(name)) as  name4
 from tablename;

2 个答案:

答案 0 :(得分:1)

first create function to split values

create function [dbo].[udf_splitstring] (@tokens    varchar(max),
                                   @delimiter varchar(5))
returns @split table (
  token varchar(200) not null )
as



  begin

      declare @list xml

      select @list = cast('<a>'
                          + replace(@tokens, @delimiter, '</a><a>')
                          + '</a>' as xml)

      insert into @split
                  (token)
      select ltrim(t.value('.', 'varchar(200)')) as data
      from   @list.nodes('/a') as x(t)

      return

  end

SELECT 
max(CASE WHEN TOKEN='CLAR'   THEN TOKEN END) 'NAME1' ,
max(CASE WHEN TOKEN='ALWIN'  THEN TOKEN END) 'NAME2', 
max(CASE WHEN TOKEN='ANTONY' THEN TOKEN END) 'NAME3', 
max(CASE WHEN TOKEN='RINU'   THEN TOKEN END) 'NAME4', 
max(CASE WHEN TOKEN='DAMI'   THEN TOKEN END) 'NAME5', 
max(CASE WHEN TOKEN='PRINCE' THEN TOKEN END) 'NAME6'
FROM #Table1 as t1
CROSS APPLY [dbo].UDF_SPLITSTRING(name,',') as t2

输出

NAME1   NAME2   NAME3   NAME4   NAME5   NAME6
clar    alwin   antony  rinu    dami    prince

答案 1 :(得分:1)

IDK如果这对您有帮助,但这就是我组织我的csv文件的方式
PS:根据您的数据

value,name1,name2,name3,name4,name5,name6
0,clar,alwin,antony,rinu,dami,prince

当我使用byulk insert时,你只需要说

BULK INSERT TableName FROM 'Location\filename.csv' WITH (ROWTERMINATOR = '\n', FIELDTERMINATOR = ',', FIRSTROW = 2)