Splitting the string in sql server

前端 未结 4 1054
独厮守ぢ
独厮守ぢ 2020-11-27 19:18

I have a string in the database which is comma separated.Like \'apple,banana,pineapple,grapes\' I need to split this string on the basis of comma and iterate through this.Si

4条回答
  •  失恋的感觉
    2020-11-27 19:47

    I have a solution using Recursion as follows

    Create function split_string(@str as nvarchar(max),@separator as char(1)) returns @myvalues Table (id int identity(1,1),myval nvarchar(100))
    as 
    --Kamel Gazzah
    --23/04/2019
    begin
    with cte as(
    select @str [mystr],
    cast(1 as int) [Start],
    charindex(@separator,@str)as Nd
    union all
    select substring(@str,nd+1,len(@str)),cast(Nd+1 as int),charindex(@separator,@str,Nd+1) from cte
    where nd>0
    )
    insert into @myvalues(myval) 
    select case when nd>0 then substring(@str,start,Nd-start) 
    else substring(@str,start,len(@str)) end [splitted] 
    from cte   OPTION (MAXRECURSION 1000);
    return ;
    end;
    

    You can call this function

    select * from split_string('apple,banana,pineapple,grapes',',')
    

提交回复
热议问题