如何根据SQL Server中的位置将字符串拆分为字符串

时间:2016-08-19 06:09:04

标签: sql-server

字符串输入:xxxxyyyyzzzz

字符串输出:xx xx yy yy zz zz

请在SQL Server中拆分上面的字符串。我正在尝试使用类似

replace函数
PARSENAME(REPLACE(@str, ',', '.'), 2)

但它无效

3 个答案:

答案 0 :(得分:1)

使用while循环。

<强>查询

DECLARE @str AS varchar(100) = 'xxxxyyyyzzzz';
DECLARE @i AS int = 1;
DECLARE @res AS varchar(250) = '';

WHILE (LEN(@str) + 1 >= @i)
BEGIN
  SET @res += SUBSTRING(@str, @i, 2) + ' ';
  SET @i = @i + 2;
END
SELECT @res as [output];

<强>结果

+-------------------+
| output            |
+-------------------+
| xx xx yy yy zz zz | 
+-------------------+

Demo

答案 1 :(得分:1)

<强> Using Numbers table..

declare @string varchar(100)='xxxxyyyyzzzz'

;With cte
as
(select case when number%2<>0 then substring(@string,number,2) else null end as new from Numbers
where number<len(@string) 
)
select replace(stuff((select 
','+new 
 from cte where new is not null
 for xml path('')),1,1,''),',', ' ')

<强>输出:
xx xx yy yy zz zz

答案 2 :(得分:0)

CTE和STUFF的另一种方式:

DECLARE @s nvarchar(max) = 'xxxxyyyyzzzz'

;WITH cte AS (
    SELECT  @s as s,
            1 as lev
    UNION ALL
    SELECT  STUFF(s,3*lev,0,' '),
            lev+1
    FROM cte
    WHERE 3*lev < LEN(s)
)

SELECT top 1 s
FROM cte
ORDER BY lev desc

输出:

xx xx yy yy zz zz