Sql 服务器 2016 在第 5 个逗号后拆分

Sql server 2016 split after 5th comma

我需要拆分以下字符串

10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29

10, 11, 12, 13, 14
15, 16, 17, 18, 19
20, 21, 22, 23, 24
25, 26, 27, 28, 29

对此有类似的答案 - 尝试以下 link:SQL Server - find nth occurrence in a string

您要做的是找到子字符串的第 N 次出现。我相信当我遇到这个问题时,我使用了上述 link 中接受的答案来解决这个问题。

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);

另一种解决方案不是很好,但它仍然在集合操作中而不是循环,如下所示:

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