sql 在一定长度的字符后拆分到新行

sql split after certain lenght of charcters to new row

我在其中一个栏目中有一条记录,如下所示:

132007700013213860001321264000          

我想根据字符长度 10 不使用任何定界符进行拆分。每 10 个字符后我需要换行记录。喜欢下面

1320077000
1321386000
1321264000                                                                                                                                                                                                             

您可以使用递归 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;

Here 是一个 db<>fiddle.

如果字符串是固定宽度的,您可以使用 3 个 SUBSTRING 函数并交叉应用到 'unpivot' 将 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

所有功劳都归功于戈登·利诺夫。我刚刚添加了转换以使其工作。

数据库 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;