How to escape underscore character in PATINDEX pattern argument?

podosta picture podosta · May 14, 2009 · Viewed 54.1k times · Source

I've found a solution for finding the position of an underscore with PATINDEX :

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

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

Have you other ideas? Like a way to escape the underscore character?

Answer

Curt Hagenlocher picture Curt Hagenlocher · May 14, 2009

I've always done it with brackets: '%[_]%'