127

我在 SQL Server 中有大字符串。我想将该字符串截断为 10 或 15 个字符

原始字符串

this is test string. this is test string. this is test string. this is test string.

所需字符串

this is test string. this is ......
4

6 回答 6

189

如果您只想返回长字符串的几个字符,您可以使用:

select 
  left(col, 15) + '...' col
from yourtable

请参阅SQL Fiddle with Demo

这将返回字符串的前 15 个字符,然后将 连接...到它的末尾。

如果你想确保小于 15 的字符串不会得到,...那么你可以使用:

select 
  case 
    when len(col)>15
    then left(col, 15) + '...' 
    else col end col
from yourtable

请参阅带有演示的 SQL Fiddle

于 2013-02-28T17:58:06.283 回答
44

您可以使用

LEFT(column, length)

或者

SUBSTRING(column, start index, length)
于 2013-02-28T18:24:05.047 回答
5

您还可以使用 Cast() 操作:

 Declare @name varchar(100);
set @name='....';
Select Cast(@name as varchar(10)) as new_name
于 2015-03-25T09:14:36.750 回答
4

我认为这里的答案很好,但我想添加一个场景。

有几次我想从字符串前面去掉一定数量的字符,而不用担心它的长度。使用 RIGHT() 和 SUBSTRING() 有几种方法可以做到这一点,但它们都需要知道字符串的长度,这有时会减慢速度。

我改用 STUFF() 函数:

SET @Result = STUFF(@Result, 1, @LengthToRemove, '')

这将用空字符串替换不需要的字符串的长度。

于 2015-02-24T23:38:51.387 回答
1

您也可以使用以下内容,iif 避免了 case 语句,仅在需要时添加省略号(仅适用于 SQL Server 2012 及更高版本),并且 case 语句更符合 ANSI(但更冗长)

SELECT 
  col, LEN(col), 
  col2, LEN(col2), 
  col3, LEN(col3) FROM (
  SELECT 
    col, 
    LEFT(x.col, 15) + (IIF(len(x.col) > 15, '...', '')) AS col2, 
    LEFT(x.col, 15) + (CASE WHEN len(x.col) > 15 THEN '...' ELSE '' END) AS col3 
  from (
      select 'this is a long string. One that is longer than 15 characters' as col
      UNION 
      SELECT 'short string' AS col
      UNION 
      SELECT 'string==15 char' AS col
      UNION 
      SELECT NULL AS col
      UNION 
      SELECT '' AS col
) x
) y
于 2017-05-31T21:11:04.747 回答
0
     CASE
     WHEN col IS NULL
        THEN ''
     ELSE SUBSTRING(col,1,15)+ '...' 
     END AS Col
于 2017-07-03T13:19:05.817 回答