How to avoid underscore in PATINDEX template argument?

I found a solution for finding underscore position with PATINDEX:

DECLARE @a VARCHAR(10) SET @a = '37_21' PRINT PATINDEX('%_%', @a) -- return 1 (false) PRINT PATINDEX('%!%', REPLACE(@a, '_', '!')) -- return 3 (correct) 

Do you have any other ideas? How to escape the underscore?

+52
regex sql-server tsql escaping sql-like
May 14 '09 at 14:09
source share
3 answers

I always did this with parentheses: '%[_]%'

+93
May 14, '09 at 14:14
source share

To combine two underscores, each of them will be enclosed in brackets

 '%[__]%' -- matches single _ with anything after '%[_][_]%' -- matches two consecutive _ 
+20
Dec 18 '12 at 15:14
source share

You can avoid using the characters [ and ] :

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

+5
Apr 11 2018-12-12T00:
source share



All Articles