如何将sql server中逗号分隔的字符串拆分为n个列

时间:2018-05-04 12:01:22

标签: sql-server string split

  1. 我有一个表 tb1 ,其中一列 OppName 为:( 8位值在 一行csv)

    ["OpportunityName","Fact","","","StartDate","EndDate","IsActive","UpdateDate"]
    

    我正在尝试将每个逗号分隔值拆分为单独的值 专栏:

          c1              c2      c3 c4 c5 c6 c7          c8
    "OpportunityName"   "Fact"    .........            "UpdateDate"
    

    我做的是:

    第1步:将字符串中的[]删除为:

       UPDATE tb1 
       SET [OppName] = REPLACE(REPLACE([OppName], '[', ''), ']', '')
    
    # output: "OpportunityName","Fact","","","StartDate","EndDate","IsActive","UpdateDate"
    

    第2步:在vars中拆分字符串,并为每一行将所有变量插入到tb2中:

    DECLARE @list varchar(8000)
    DECLARE @pos INT
    DECLARE @len INT
    DECLARE @value varchar(8000)
    DECLARE @x nvarchar(max)
    
    SET @list = '"OpportunityName","Fact","","","StartDate","EndDate","IsActive","UpdateDate",'
    
    set @pos = 0
    set @len = 0
    
    WHILE CHARINDEX(',', @list, @pos+1)>0
    BEGIN
        set @len = CHARINDEX(',', @list, @pos+1) - @pos
        set @value = SUBSTRING(@list, @pos, @len)
        set @value = REPLACE (@value, '"', '')       
        PRINT @value -- for debug porpose  
        set @pos = CHARINDEX(',', @list, @pos+@len) +1
        --Append values to x
        set @x =  (@x  +','+ @value) 
    END
    
      PRINT @x
       --Inserting in tb2
      Insert into  tb2 values(@x)
    

    但字符串没有正确连接

    有人可以帮我吗

1 个答案:

答案 0 :(得分:0)

SQL 2016具有STRING_SPLIT功能。与PIVOT结合使用,您可以执行以下操作:

;WITH CTE AS (
    SELECT value, ColumnName = 'c' + CAST(ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS VARCHAR)
    FROM STRING_SPLIT('"OpportunityName","Fact","","","StartDate","EndDate","IsActive","UpdateDate"',',')
)
SELECT * 
FROM CTE
pivot (MAX(value) FOR ColumnName IN("c1","c2","c3","c4","c5","c6","c7","c8")) AS p;

enter image description here