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
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',',')