我有一个像'aabbcczx'这样的字符串,我需要将该字符串除以2个字符。 预期的结果是这样的:
aabbcczx aa
aabbcczx bb
aabbcczx cc
aabbcczx zx
我该怎么做? 还应考虑字符串的长度逐行更改。
谢谢
答案 0 :(得分:1)
如果总是2个字符:
SELECT A.Val,
CA1.N,
SUBSTRING(A.Val,n,2)
FROM (
VALUES ('aabbcczx')
) AS A(Val)
CROSS
APPLY dbo.GetNums(1,LEN(A.Val)) AS CA1
WHERE CA1.n % 2 = 1;
GetNums是一个数字表/演算表生成器,您可以在线找到一些资源。
它将提供每个字符的位置,我们可以在substring
起始位置使用它。 where子句使用MOD
来表示,因此我们仅显示所有其他起始位置
答案 1 :(得分:0)
您可以使用递归查询:
with cte as (
select convert(varchar(max), left(str, 2)) as val2, convert(varchar(max), stuff(str, 1, 2, '')) as rest, str
from (values ( 'aabbcczx' )) v(str)
union all
select left(rest, 2) as val2, stuff(rest, 1, 2, '') as rest, str
from cte
where rest <> ''
)
select str, val2
from cte;
答案 2 :(得分:0)
您可以使用递归查询来提取字符对:
with instring as
( select 'aabbcczx' as s )
, splitter as
(
select s, substring(s, 1, 2) as rslt, 3 as next -- first two chars
from instring
union all
select s, substring(s, next, 2), next + 2 -- next two chars
from splitter
where len(s) >= next
)
select *
from splitter
请参见dbfiddle