4

我有以下示例字符串:

这个字符串非常大,有 160 多个字符。我们可以用子字符串剪切它,所以它只有 160 个字符,但它会剪切最后一个看起来有点愚蠢的单词。

现在我想要大约 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) 

结果:

这个字符串非常大,有 160 多个字符。我们可以用子字符串剪切它,所以它只有 160 个字符,但它会剪切最后一个单词 l

现在我需要找到一种方法来完成最后一个单词,在这种情况下是单词looks

任何想法什么是解决这个问题的最佳方法?

4

2 回答 2

8
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 
于 2013-08-28T22:45:08.597 回答
6

如果你选择 160,你的最后一句话是that。如果你去 165,你的最后一句话是looks。以下是使用 160 的方法:

declare @string varchar(1000)
select @string = '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 SUBSTRING(@string, 1, charindex(' ',@string,160)-1)

注意:这将在少于 160 个字符的字符串上出错。请参阅 Martin Smith 处理这种情况的答案。

于 2013-08-28T22:45:30.530 回答