我有以下示例字符串:
此字符串非常大,超过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
任何想法是解决此问题的最佳方法吗?
答案 0 :(得分: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
答案 1 :(得分: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个字符的字符串,这会出错。请参阅马丁史密斯处理这种情况的答案。