Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MSSQL子字符串并保持最后一个单词的完整性_Sql_Sql Server_Substring - Fatal编程技术网

MSSQL子字符串并保持最后一个单词的完整性

MSSQL子字符串并保持最后一个单词的完整性,sql,sql-server,substring,Sql,Sql Server,Substring,我有以下示例字符串: 这个字符串非常大,超过160个字符。我们可以用子字符串来剪切它,这样它只有160个字符,但它会剪切最后一个看起来有点愚蠢的单词 现在我想要大约160个字符,所以我使用substring() 其结果是: 这个字符串非常大,超过160个字符。我们可以用子字符串来剪切它,所以它只有160个字符,但它会剪切l最后一个单词 现在我需要找到一种方法来结束最后一个单词,在这种情况下,这个单词看起来像 你知道解决这个问题的最佳方法是什么吗?如果你选择160,你的最后一句话是那。如果你去16

我有以下示例字符串:

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

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

其结果是:

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

现在我需要找到一种方法来结束最后一个单词,在这种情况下,
这个单词看起来像


你知道解决这个问题的最佳方法是什么吗?

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

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 
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关于处理这种情况的回答。

限制是160个字符吗?如果是这样,您可能希望从生成的子字符串中删除部分单词。在这种情况下,限制为180。所以我需要完成最后一个单词(
本例中的looks
)应该添加一个case语句,以便在160处或之后没有空格时不会失败。只有一个问题,当我少于160个字符时,它将给出一个错误。@MartinSmith是的,当我看到你的答案时,我也意识到了这一点。替换
charindex(…)-1
带有
ISNULL(NULLIF(charindex(…),0)-1999999)
可能会解决字符串长度小于160个字符的问题。@s.Visser-谢谢!我怀疑
案例
是否有必要进行短暂删除。
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)