在字符串

时间:2015-12-19 07:59:42

标签: sql-server tsql replace split

如下所示的列,如何以仍然必须将一列放入逗号以搜索两个字符的方式编写查询。

实施例

'aa,aa,aa,aa,aa,aa,aa,aa,aa,aa'将成为。

感谢。

enter image description here

2 个答案:

答案 0 :(得分:3)

使用recursive ctefor xml的另一种方法:

declare @tbl as table (id int, field varchar(200))
insert into @tbl 
values (1, 'aabbccddeeffgghhgg'),
       (2, 'aabbccddeeffgghhgg')

;with cte 
      as (select id, field, n = 1
          from @tbl
          union all
          select id, field, n = n + 1
          from cte
          where n < len(field))

     select distinct a.id,
            stuff((select ',' + substring(b.field,b.n,2)
                   from    cte AS b
                   where   b.id = a.iD and b.n%2 = 1
                   order by b.id, b.n
                   for XML PATH('')),1,1,'') AS Field
     from cte as a

<强> test is here

答案 1 :(得分:2)

您可以使用下面的tsql脚本插入&#34;,&#34;每2个字符:

DECLARE @Char VARCHAR(800) = 'aaaaaaaaaaaaaaaaaaaaaaa' --sample data

DECLARE @TotalChar INT = LEN(@Char)
DECLARE @Counter INT = @TotalChar

WHILE @Counter >= 1
BEGIN

    IF @Counter % 2 = 0 AND @Counter + 1 <= @TotalChar
    BEGIN
        SET @Char = STUFF(@Char, @Counter + 1, 0, ', ')
    END

    SET @Counter = @Counter - 1
END

SELECT @Char --result data