How to escape underscore character in PATINDEX pattern argument?

痞子三分冷 提交于 2019-11-30 10:42:48

问题


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?


回答1:


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




回答2:


To match two underscores, each must be bracketed

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

'%[_][_]%' -- matches two consecutive _



回答3:


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

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



来源:https://stackoverflow.com/questions/863534/how-to-escape-underscore-character-in-patindex-pattern-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!