字符串输入:xxxxyyyyzzzz
字符串输出:xx xx yy yy zz zz
请在SQL Server中拆分上面的字符串。我正在尝试使用类似
的replace
函数
PARSENAME(REPLACE(@str, ',', '.'), 2)
但它无效
答案 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 |
+-------------------+
答案 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