¿Cómo escapar del carácter de subrayado en el argumento PATINDEX pattern?


He encontrado una solución para encontrar la posición de un subrayado con PATINDEX:

DECLARE @a VARCHAR(10)  
SET     @a = '37_21'

PRINT PATINDEX('%_%', @a)                    -- return 1 (false)
PRINT PATINDEX('%!%', REPLACE(@a, '_', '!')) -- return 3 (correct)

¿Tiene otras ideas? ¿Como una forma de escapar del carácter de subrayado?

Author: abatishchev, 2009-05-14

3 answers

Siempre lo he hecho con corchetes: '%[_]%'

 104
Author: Curt Hagenlocher,
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-12-16 22:41:41

Para que coincida con dos guiones bajos, cada uno debe estar entre corchetes

'%[__]%' -- matches single _ with anything after

'%[_][_]%' -- matches two consecutive _
 21
Author: Leif Neland,
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-05-07 23:11:42

Puedes escapar usando los caracteres [ y ] así:

PRINT PATINDEX('%[_]%', '37_21')

 5
Author: Charlie,
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
2012-10-26 20:59:35