I need to split the following string
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
to
10, 11, 12, 13, 14
15, 16, 17, 18, 19
20, 21, 22, 23, 24
25, 26, 27, 28, 29
I need to split the following string
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
to
10, 11, 12, 13, 14
15, 16, 17, 18, 19
20, 21, 22, 23, 24
25, 26, 27, 28, 29
create function dbo.SplitString (@string varchar(max), @delimiter char(1), @Occurence int)
returns @t table
(
String varchar(max)
)
as
begin
declare @i int = 0
, @k int = 1
, @j int = 0
, @str varchar(max);
if right(@string, 1) <> ','
set @string = @string + ',';
while CHARINDEX(@delimiter, @string, @i + 1) > 0
begin
set @i = CHARINDEX(@delimiter, @string, @i + 1);
set @j = @j + 1;
if @j = @Occurence or CHARINDEX(@delimiter, @string, @i + 1) = 0
begin
insert into @t (String)
select SUBSTRING (@string, @k, @i - @k);
set @k = @i + 1;
set @j = 0;
end
end
return;
end
select *
from dbo.SplitString ('10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29', ',', 5);
There are similar answers to this - try the following link: SQL Server - find nth occurrence in a string
What you're looking to do is find the Nth occurrence of a substring. I believe that I used the accepted answer in the aforementioned link to solve this when I had this issue.
Another solution which is not so great but its still in set operation instead of loop as below:
Declare @str varchar(100) = '10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25'
;With cte as
(
select RowN = Row_Number() over (order by (SELECT NULL)), *, SplitValue= Case When (Row_Number() over (order by (Select NULL)) % 5 = 0 ) then [Value]+ '$' else [Value] end
from string_Split(@str, ',')
)
Select * from string_split( Stuff((Select ', ' + SplitValue from cte for xml path('')),1,1,''), '$')