[英]sql split after certain lenght of charcters to new row
我在其中一列中有记录,如下所示:
132007700013213860001321264000
我想在不使用任何基于 char 长度 10 的分隔符的情况下进行拆分。每 10 个字符后,我需要在新行中记录。 如下所示
1320077000
1321386000
1321264000
如果字符串是固定宽度,您可以使用 3 个 SUBSTRING 函数和 CROSS APPLY 将 3 列“取消透视”为 1 列,称为“new_col”。
declare @txtTable table(txt char(30) not null)
insert @txtTable(txt) values
('132007700013213860001321264000'),
('999999999999999999999999999999');
select u.*
from @txtTable t
cross apply (values (substring(t.txt, 1, 10),
substring(t.txt, 11, 10),
substring(t.txt, 21, 10))) v(c1, c2, c3)
cross apply (values (v.c1),(v.c2),(v.c3)) u(new_col);
new_col
1320077000
1321386000
1321264000
9999999999
9999999999
9999999999
您可以使用递归 CTE:
with cte as (
select left(col, 10) as x10, convert(varchar(max), stuff(col, 1, 10, '')) as rest
from t
union all
select left(rest, 10), stuff(rest, 1, 10, '')
from cte
where rest <> ''
)
select x10
from cte;
这是一个 db<>fiddle。
所有功劳归功于戈登·林诺夫。 我只是添加了铸造以使其工作。
DB Fiddle 示例以某种方式工作,但在 SSMS 中这是一个错误。
SQL
DECLARE @tbl TABLE (col VARCHAR(30));
INSERT @tbl (col) VALUES
('132007700013213860001321264000'),
('999999999999999999999999999999');
WITH cte as
(
SELECT CAST(LEFT(col, 10) AS VARCHAR(10)) as x10, CAST(stuff(col, 1, 10, '') AS VARCHAR(MAX)) as rest
FROM @tbl
UNION ALL
SELECT CAST(LEFT(rest, 10) AS VARCHAR(10)), STUFF(rest, 1, 10, '')
FROM cte
WHERE rest <> ''
)
SELECT x10
FROM cte;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.