Transact-SQL - Select 值并添加自定义字符串如果值太长

Transact-SQL - Select Value and add custom String If value is too long

我整理了一个很长的声明,其中包括从 table 中选择不同的产品名称。在我的应用程序中,我想将此名称的长度限制为 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) '...')

但这只会给我一个错误。

使用case表达式:

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

如果你想要一个“干净”的休息,即不把一个词切成两半,你可以使用它来提供这个:

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