我有以下示例字符串:



现在我想要大约 160 个字符,所以我使用 substring()

SELECT SUBSTRING('This string is very large, it has more then 160 characters.
We can cut it with substring so it just has 160 characters but then it cuts
of the last word that looks kind of stupid.', 0 , 160)

结果如下:



现在我需要找到一种方法来完成最后一个单词,在这种情况下是单词 looks
任何想法解决这个问题的最佳方法是什么?

最佳答案

DECLARE @S VARCHAR(500)= 'This string is very large, it has more then 160 characters.
    We can cut it with substring so it just has 160 characters but then it cuts
    of the last word that looks kind of stupid.'

SELECT CASE
         WHEN charindex(' ', @S, 160) > 0 THEN SUBSTRING(@S, 0, charindex(' ', @S, 160))
         ELSE @S
       END

关于sql - MSSQL 子串并保持最后一个字不变,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18499409/

10-15 04:06