SQL Server:根据LEN规则将文本字段拆分为多行

时间:2017-04-17 20:07:14

标签: sql sql-server

有一个由IDNotes,LEN(笔记)和LEN / 60

组成的表格

我需要将其分解为LEN = 60的块,添加一个新的“LINE”列,每行增加1。

所以:

1 | Super long text of 150 characters | 150 | 3

变为:

 - 1 | 1 | Super long text of 150
 - 1 | 2 | characters is much more
 - 1 | 3 | manageable!

我创建了LEN和LEN / 60数据,以防段值在某种循环语句中有用。

递归CTE,循环,变量 - 此时我几乎可以接受任何事情!

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

是。 CTE就是答案。请试试这个。

WITH cte_base AS(SELECT ID
                    , 1 AS IDLN
                    , LTRIM(RTRIM(Notes)) AS Notes
                    , 1 AS Rownum
                FROM yourtable
), cte_re AS ( SELECT Id
                    , IDLN
                    , 1 AS StartPos
                    , CAST(60 - CHARINDEX(' ', REVERSE(LEFT(SUBSTRING(Notes, 1, 60) + ' ', 60))) AS INT) StringLen
                FROM cte_base
                WHERE Rownum =1
                UNION ALL
                SELECT r.Id
                    , r.IDLN + 1 
                    , StartPos + StringLen + 1
                    , CAST(60 - CHARINDEX(' ', REVERSE(LEFT(SUBSTRING(b.Notes, StartPos + StringLen + 1, 60) + ' ', 60))) AS INT) 
                FROM CTE_re  r
                INNER JOIN cte_base b 
                    ON b.Id = r.Id and b.rownum = 1
                WHERE StartPos + StringLen <= DATALENGTH(b.Notes) 
)       
SELECT r.Id
    , r.IDLN 
    , UPPER(SUBSTRING(b.Notes, r.StartPos, r.StringLen)) AS Notes
FROM cte_re r
INNER JOIN cte_base b
ON r.Id = b.Id;