Cómo truncar una cadena usando SQL server


Tengo una cadena grande en SQL Server. Quiero truncar esa cadena a 10 o 15 caracteres

Cadena original

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

Cadena deseada

this is test string. this is ......
Author: alroc, 2013-02-28

6 answers

Si solo desea devolver unos pocos caracteres de su cadena larga, puede usar:

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

Ver Violín SQL con Demo.

Esto devolverá los primeros 15 caracteres de la cadena y luego concatena el ... al final de la misma.

Si desea asegurarse de que las cadenas de menos de 15 no obtienen el ... entonces puede usar:

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

Ver Violín SQL con Demo

 122
Author: Taryn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-28 20:11:57

Puedes usar

LEFT(column, length)

O

SUBSTRING(column, start index, length)
 19
Author: snaplemouton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-02 09:04:41

Creo que las respuestas aquí son geniales, pero me gustaría agregar un escenario.

Varias veces he querido tomar una cierta cantidad de caracteres del frente de una cadena, sin preocuparme por su longitud. Hay varias maneras de hacer esto con RIGHT() y SUBSTRING(), pero todos necesitan saber la longitud de la cadena que a veces puede ralentizar las cosas.

He usado la función STUFF () en su lugar:

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

Esto reemplaza la longitud de la cadena innecesaria con una cadena vacía.

 4
Author: Dan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-24 23:38:51

También puedes usar la operación Cast ():

 Declare @name varchar(100);
set @name='....';
Select Cast(@name as varchar(10)) as new_name
 3
Author: goli55,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-25 09:14:36

También puede usar lo siguiente, el iif evita la instrucción case y solo agrega elipses cuando es necesario (solo es bueno en SQL Server 2012 y posteriores) y la instrucción case es más compatible con ANSI (pero más detallada)

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
 1
Author: Gregory Blajian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-31 21:11:04
     CASE
     WHEN col IS NULL
        THEN ''
     ELSE SUBSTRING(col,1,15)+ '...' 
     END AS Col
 0
Author: dLight,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-03 13:19:05