Subcadena T-SQL-Últimos 3 caracteres


Usando T-SQL, ¿cómo conseguiría los últimos 3 caracteres de una columna varchar?

Por Lo tanto el texto de la columna es IDS_ENUM_Change_262147_190 y necesito 190

Author: ROMANIA_engineer, 2011-12-02

5 answers

SELECT RIGHT(column, 3)

Eso es todo lo que necesitas.

También puedes hacer LEFT() de la misma manera.

Tenga en cuenta que si está usando esto en una cláusula WHERE, RIGHT() no puede usar ningún índice.

 92
Author: JNK,
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
2011-12-02 16:55:37

Puedes usar de cualquier manera:

SELECT RIGHT(RTRIM(columnName), 3)

O

SELECT SUBSTRING(columnName, LEN(columnName)-2, 3)
 13
Author: Elias Hossain,
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
2011-12-02 17:13:53

Porque más formas de pensar en ello siempre son buenas:

select reverse(substring(reverse(columnName), 1, 3))
 6
Author: Ben Thul,
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
2011-12-02 18:35:21
declare @newdata varchar(30)
set @newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(@newdata),0,charindex('_',reverse(@newdata))))

=== Explicación ===

Me resultó más fácil leer escrito así:

SELECT
    REVERSE( --4.
        SUBSTRING( -- 3.
            REVERSE(<field_name>),
            0,
            CHARINDEX( -- 2.
                '<your char of choice>',
                REVERSE(<field_name>) -- 1.
            )
        )
    )
FROM
    <table_name>
  1. Invertir el texto
  2. Busque la primera aparición de un carácter específico (es decir, la primera aparición del FINAL del texto). Obtiene el índice de este carácter
  3. Vuelve a mirar el texto invertido. busca desde el índice 0 hasta el índice de tu char. Esto da la cadena que está buscando, pero al revés
  4. Invirtió la cadena invertida para darle la subcadena deseada
 1
Author: user2176274,
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-01-04 10:47:10

Si desea encontrar específicamente cadenas que terminen con los caracteres deseados, esto le ayudaría...

select * from tablename where col_name like '%190'
 -3
Author: sharath,
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
2014-03-24 19:35:42