如何在PATINDEX模式参数中转义下划线字符?


71

我找到了一种使用PATINDEX查找下划线位置的解决方案:

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

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

还有其他想法吗?喜欢逃脱下划线字符的方法吗?

Answers:



26

要匹配两个下划线,每个下划线都必须放在方括号中

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

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

6

您可以使用[]字符进行转义,如下所示:

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.