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

标签 sql sql-server tsql

有没有一种方法可以将字符串(来自特定列)拆分为 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.

结果:

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.

我知道我可以使用 charindex 来查找最后一个空格,但我不确定如何获取剩余的空格并将它们作为行返回。

最佳答案

尝试这样的事情。也许您可以创建以下实现的 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

输出将是这样的:

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.

关于sql - 将 SQL Server 中的字符串拆分为最大长度,将每个字符串作为一行返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10852612/

相关文章:

sql-server - Select WITHOUT WHERE 或 ORDER BY 子句的结果排序顺序

sql - 如何用sql计算累计时间差

MySql加入多选子查询

c# - DapperExtensions在插入操作时产生“无效的对象名称”

sql-server - 分区主明细表

sql - 如何生成序列号+在select语句中添加1

sql - 如何在没有额外 XML 开销的情况下在 T SQL 中对 XML 进行编码

SQL:使用计算字符串作为表名,连接select的所有行进行统计

mysql-使用多个where子句更新单行中的多个列

mysql - 编写如何删除扩展名并放入单独列的脚本