74

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
podosta
  • 1,922
  • 1
  • 17
  • 15

3 Answers3

124

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

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Curt Hagenlocher
  • 20,680
  • 8
  • 60
  • 50
  • 8
    +1 see: http://msdn.microsoft.com/en-us/library/ms187489(SQL.90).aspx, Section "Searching for Wildcard Characters" – Tomalak May 14 '09 at 14:17
27

To match two underscores, each must be bracketed

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

'%[_][_]%' -- matches two consecutive _
Leif Neland
  • 1,416
  • 1
  • 17
  • 40
6

You can escape using the [ and ] characters like so:

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

Ryan Gates
  • 4,501
  • 6
  • 50
  • 90
Charlie
  • 61
  • 1
  • 1