sql server split comma separated values into columns

前端 未结 3 1010
青春惊慌失措
青春惊慌失措 2020-12-19 07:30

I trying to split the csv to individual columns

SAMPLE DATA

PAR_COLUMN  PERIOD  VALUE       mul_query
----------  ------  ---------         


        
3条回答
  •  太阳男子
    2020-12-19 08:16

    Dynamically solve this problem, use DSQL to add more columns in the result accordingly.

    --create split function
    CREATE FUNCTION [dbo].[SO_Split]
    (
        @List nvarchar(2000),
        @SplitOn nvarchar(5)
    ) 
    RETURNS @RtnValue table
    (
    
        Id int identity(1,1),
        Value nvarchar(100)
    )
    AS 
    BEGIN
    While (Charindex(@SplitOn,@List)>0)
    Begin
    Insert Into @RtnValue (value)
    Select
        Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1)))
        Set @List =Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))
    End
        Insert Into @RtnValue (Value)
        Select Value = ltrim(rtrim(@List))
        Return
    END
    
    --below is the dynamic solution for this problem
    declare @sql nvarchar(3000) = 'select *'
    declare @cnt int = 1
    declare @rowNum int = (select max(a) from (select(select max(id) as id_max from dbo.so_split(mul_query,'*')) as a from #test) as b)
    
    while(@cnt <= @rowNum)
    begin
        set @sql = @sql + N', ISNULL((select value from dbo.so_split(mul_query,''*'') where id = '+cast(@cnt as nvarchar(5))+N'),''1'')'
        set @cnt = @cnt + 1
    end
    
    set @sql = @sql + N' from #test'
    
    exec sp_executesql @sql
    

    The result is attached below.

提交回复
热议问题