【问题标题】:MSSQL Substring and keep the last word intactMSSQL 子字符串并保持最后一个单词完整
【发布时间】:2013-09-01 04:56:34
【问题描述】:

我有以下示例字符串:

这个字符串很大,有超过 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

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

【问题讨论】:

  • 限制为 160 个字符吗?如果是这样,您可能希望从结果子字符串中删除部分单词。
  • 在这种情况下,限制是 180。所以我需要完成最后一个单词(本例中为 looks

标签: sql sql-server substring


【解决方案1】:
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 

【讨论】:

  • @S.Visser - 谢谢!我怀疑CASE 是否有必要暂时删除。
【解决方案2】:

如果你选择 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 处理这种情况的答案。

【讨论】:

  • 应该添加一个case语句,这样如果160或之后没有空格就不会失败
  • 只有一个问题,当我的字符少于 160 个时,它会报错。
  • @MartinSmith 是的,当我看到你的回答时,我也意识到了这一点。
  • ISNULL(NULLIF(charindex(...), 0) - 1, 999999) 替换charindex(...) - 1 可能会解决字符串长度小于160 个字符的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多