How to split a comma-separated value to columns

后端 未结 30 4052
刺人心
刺人心 2020-11-21 04:38

I have a table like this

Value   String
-------------------
1       Cleo, Smith

I want to separate the comma delimited string into two colu

30条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 05:00

    ALTER function get_occurance_index(@delimiter varchar(1),@occurence int,@String varchar(100))
    returns int
    AS Begin
    --Declare @delimiter varchar(1)=',',@occurence int=2,@String varchar(100)='a,b,c'
    Declare @result int
     ;with T as (
        select 1 Rno,0 as row, charindex(@delimiter, @String) pos,@String st
        union all
        select Rno+1,pos + 1, charindex(@delimiter, @String, pos + 1), @String
        from T
        where pos > 0
    )
    select  @result=pos 
    from T 
    where pos > 0   and rno = @occurence 
    return isnull(@result,0)
    ENd
    
    
    declare @data as table (data varchar(100))
    insert into @data values('1,2,3') 
    insert into @data values('aaa,bbbbb,cccc') 
    select top  3 Substring (data,0,dbo.get_occurance_index( ',',1,data)) ,--First Record always starts with 0
    Substring (data,dbo.get_occurance_index( ',',1,data)+1,dbo.get_occurance_index( ',',2,data)-dbo.get_occurance_index( ',',1,data)-1) ,
    Substring (data,dbo.get_occurance_index( ',',2,data)+1,len(data)) , -- Last record cant be more than len of actual data
    data 
    From @data 
    

提交回复
热议问题