Split multiple string's into multiple columns

后端 未结 4 1391
深忆病人
深忆病人 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:19

    If you have atmost three values then try this.

    DECLARE @str1 VARCHAR(max) = 'A1,A2,A3'
    
    SELECT Parsename(Replace(@str1, ',', '.'), 3) 'FST_COL',
           Parsename(Replace(@str1, ',', '.'), 2) 'SCD_COL',
           Parsename(Replace(@str1, ',', '.'), 1) 'TRD_COL' into #temp
    

    Or

    DECLARE @str1 VARCHAR(max) = 'A1,A2,A3',
            @sql  NVARCHAR(max),
            @loop INT,
            @cnt  INT=1
    
    SELECT @loop = Len(@str1) - Len(Replace(@str1, ',', '')) + 1
    
    SET @sql=' WITH Split_cols ( xmlcol)
         AS (SELECT CONVERT(XML, ''''
                                 + Replace('''
             + @str1 + ''', '','', '''') + '''') as xmlcol)
    
    SELECT '
    
    WHILE @cnt <= @loop
      BEGIN
          SET @sql+=' xmlcol.value(''/cols[1]/col['
                    + CONVERT(VARCHAR(30), @cnt)
                    + ']'', ''varchar(100)'') AS col'
                    + CONVERT(VARCHAR(30), @cnt) + ','
          SET @cnt=@cnt + 1
      END
    
    SET @sql=LEFT(@sql, Len(@sql) - 1)
    SET @sql +=' FROM   Split_cols '
    
    --PRINT @sql
    
    EXEC Sp_executesql @sql 
    

提交回复
热议问题