S.V*_*ser 4 sql sql-server substring
我有以下示例字符串:
这个字符串非常大,它有超过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)
Run Code Online (Sandbox Code Playgroud)
结果如下:
这个字符串非常大,它有超过160个字符.我们可以用子串切割它,因此它只有160个字符,但随后它切掉了l的最后一个字
现在我需要找到一种方法来完成最后一个单词,在这个例子中是单词 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
Run Code Online (Sandbox Code Playgroud)
如果你选择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)
Run Code Online (Sandbox Code Playgroud)
注意:对于少于160个字符的字符串,这将出错.请参阅Martin Smith对处理这种情况的回答.
| 归档时间: |
|
| 查看次数: |
939 次 |
| 最近记录: |