1

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
S3S
  • 24,809
  • 5
  • 26
  • 45
ram kumar
  • 187
  • 1
  • 1
  • 16

3 Answers3

1
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);
Dean Savović
  • 739
  • 3
  • 7
  • 5
    Of all the splitters out there this is the absolute worst for performance. It is a multi-statement table valued function using loops inside. Here are several options that are MUCH better. http://sqlperformance.com/2012/07/t-sql-queries/split-strings Since we are wanting a specific position within the results I would prefer a different splitter. The one from Jeff Moden. http://www.sqlservercentral.com/articles/Tally+Table/72993/ It has the advantage of returning the position that none of the splitters do. – Sean Lange Jun 09 '17 at 14:10
  • If we split into 6, the last two value is not showing – ram kumar Jun 09 '17 at 14:14
  • @ramkumar added functionality for Occurence = 6 or whatewer – Dean Savović Jun 09 '17 at 14:32
  • @SeanLange, I absolutely agree with you. – Dean Savović Jun 09 '17 at 14:32
0

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.

Eli
  • 2,538
  • 1
  • 25
  • 36
0

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,''), '$')
Kannan Kandasamy
  • 13,405
  • 3
  • 25
  • 38