Split multiple string's into multiple columns

后端 未结 4 1399
深忆病人
深忆病人 2020-12-22 13:55

I have the following three different strings which needs to split into three different columns.

Example:

String 1:

Declare @         


        
4条回答
  •  孤城傲影
    2020-12-22 14:07

    I know its a bit heavy but it will work

    Declare @str1 varchar(max) = 'A1,A2,A3'
    Declare @str2 varchar(max) = 'B1,B2,B3'
    Declare @str3 varchar(max) = 'C1,C2,C3'
    
    DECLARE @RowCount TINYINT
    DECLARE @i        TINYINT = 0
    
    DECLARE @Table AS TABLE
    
    (
     colA  varchar(MAX)
    ,ColB varchar(MAX)
    ,ColC varchar(MAX)
    
    )
    
    SET @RowCount =  len(@str1) - len(replace(@str1, ',', ''))
    
    WHILE(@i<=@RowCount)
    BEGIN
        INSERT INTO @Table
        SELECT  LEFT(@str1,CHARINDEX(',',@str1+',',0)-1) AS colA
               ,LEFT(@str2,CHARINDEX(',',@str2+',',0)-1) AS colB
               ,LEFT(@str3,CHARINDEX(',',@str3+',',0)-1) AS colC
    
        SET @str1 = STUFF(@str1,1,CHARINDEX(',',@str1,0),'')
        SET @str2 = STUFF(@str2,1,CHARINDEX(',',@str2,0),'')
        SET @str3 = STUFF(@str3,1,CHARINDEX(',',@str3,0),'')
    
        SET @i = @i + 1
    
    END
    
    SELECT * FROM @Table
    

提交回复
热议问题