【问题标题】:Transact-SQL - Select Value and add custom String If value is too longTransact-SQL - 如果值太长,则选择值并添加自定义字符串
【发布时间】:2021-06-30 01:28:01
【问题描述】:

我整理了一个很长的声明,其中包括从表中选择不同的产品名称。在我的应用程序中,我想将此名称的长度限制为 100 个字符。到目前为止,我已经通过在查询中使用 LEFT(product_name, 100) 实现了这一点。但是,我想在值中添加一个“...”,以防名称实际上超过 100 个字符,以便用户知道实际值比他看到的长一点。

如果我的数据库中只有 2 件产品:

1: 'Awesome product'
2: 'Another totally awsome product that will make your life a lot better if you buy it because it is really awesome in many ways.'

结果应该是这样的:

1: 'Awesome product'
2: 'Another totally awsome product that will make your life a lot better if you buy it because it is rea...'

如何使用简单的 SELECT 查询来做到这一点?我的第一直觉是尝试使用 IF:

SELECT LEFT(product_name, 100) + (IF LEN(product_name > 100) '...')

但这只会给我一个错误。

【问题讨论】:

  • 如果截断任何字符上的字符串足够好,或者您想在最接近的整个单词处将其中断?

标签: sql tsql if-statement select string-length


【解决方案1】:

使用case 表达式:

(case when len(product_name) <= 100 then product_name
      else left(product_name, 97) + '...'
 end) as new_product_name

【讨论】:

  • 谢谢,这就是我要找的。​​span>
【解决方案2】:

如果你想要一个“干净”的休息时间,只需提供这个作为你可以使用的东西,即不把一个词切成两半:

declare @string varchar(200)='Another totally awsome product that will make your life a lot better if you buy it because it is really awesome in many ways.', @len tinyint=100
select
case when len(@string)>@len 
    then Stuff(@string,@len+1-CharIndex(' ', (Reverse(Left(@string,@len)))),200,'...')
else @string end

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多