1

我需要拆分以下字符串

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
4

3 回答 3

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);
于 2017-06-09T14:08:42.390 回答
0

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

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

于 2017-06-09T14:08:41.803 回答
0

另一个不是很好但仍处于设置操作而不是循环的解决方案,如下所示:

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,''), '$')
于 2017-06-09T14:27:21.077 回答