How to escape underscore character in PATINDEX pat

2019-02-01 03:39发布

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?

3条回答
Rolldiameter
2楼-- · 2019-02-01 03:53

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

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

查看更多
姐就是有狂的资本
3楼-- · 2019-02-01 03:58

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

查看更多
看我几分像从前
4楼-- · 2019-02-01 04:13

To match two underscores, each must be bracketed

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

'%[_][_]%' -- matches two consecutive _
查看更多
登录 后发表回答