将SQL Server中的字符串拆分为最大长度,将每个字符串作为一行返回

Dan*_*ite 5 sql t-sql sql-server

有没有办法将字符串(从特定列)拆分为n个字符而不会破坏单词,每个结果都在自己的行中?

例:

2012-04-24 Change request #3 for the contract per terms and conditions and per John Smith in the PSO department  Customer states terms should be Net 60 not Net 30.  Please review signed contract for this information.
Run Code Online (Sandbox Code Playgroud)

结果:

2012-04-24 Change request #3 for the contract per terms and conditions and per John Smith in the
PSO department  Customer states terms should be Net 60 not Net 30.
Please review signed contract for this information.
Run Code Online (Sandbox Code Playgroud)

我知道我可以charindex用来找到最后一个空格,但我不知道我怎么能得到剩下的空间并将它们作为行返回.

Fir*_*ari 4

尝试这样的事情。也许您可以创建以下实现的 SQL 函数。

DECLARE @Str VARCHAR(1000)
SET @Str = '2012-04-24 Change request #3 for the contract per terms and conditions and per John Smith in the PSO department  Customer states terms should be Net 60 not Net 30.  Please review signed contract for this information.'

DECLARE @End INT
DECLARE @Split INT

SET @Split = 100

declare @SomeTable table
(
  Content varchar(3000)
)


WHILE (LEN(@Str) > 0)
BEGIN
    IF (LEN(@Str) > @Split)
    BEGIN
        SET @End = LEN(LEFT(@Str, @Split)) - CHARINDEX(' ', REVERSE(LEFT(@Str, @Split)))
        INSERT INTO @SomeTable VALUES (RTRIM(LTRIM(LEFT(LEFT(@Str, @Split), @End))))
        SET @Str = SUBSTRING(@Str, @End + 1, LEN(@Str))
    END
    ELSE
    BEGIN
        INSERT INTO @SomeTable VALUES (RTRIM(LTRIM(@Str)))
        SET @Str = ''
    END
END

SELECT *
FROM @SomeTable
Run Code Online (Sandbox Code Playgroud)

输出将是这样的:

2012-04-24 Change request #3 for the contract per terms and conditions and per John Smith in the
PSO department  Customer states terms should be Net 60 not Net 30.  Please review signed contract
for this information.
Run Code Online (Sandbox Code Playgroud)