在下面的代码示例中,所有结果都应返回7.
那些以X开头的别名的人不会。
select
--where matches
patindex('%-%' ,'111111-11') dash --not a special character, so works without escaping
,patindex('%[%' ,'111111[11') xLeftCrotchet --special character [ not escaped; works
,patindex('%[[]%','111111[11') leftCrotchetEscaped --special character [ escaped to [[]; doesn't work
,patindex('%]%' ,'111111]11') rightCrotchet --special character ] not escaped; doesn't work
,patindex('%[]]%','111111]11') xRightCrotchetEscaped --special character ] escaped to []]; also doesn't work
--where doesn't match
,patindex('%[^-]%' ,'------1--') dash --not a special character, so works without escaping
,patindex('%[^[]%' ,'[[[[[[1[[') leftCrotchet --special character [ not escaped; works
,patindex('%[^[[]]%','[[[[[[1[[') xLeftCrotchetEscaped --special character [ escaped to [[]; doesn't work
,patindex('%[^]]%' ,']]]]]]1]]') xRightCrotchet --special character ] not escaped; doesn't work
,patindex('%[^[]]]%',']]]]]]1]]') xRightCrotchetEscaped --special character ] escaped to []]; also doesn't work
在某些情况下,为什么这不起作用是有道理的;即未正确转义特殊字符的地方。
然而,对于左手四分音符,它是否需要被转义取决于它是否遵循插入符号(即我们是否匹配此字符,或者除了此字符之外的所有字符)。
对于正确的四分音符,除了正确的四分音符之外似乎没有办法匹配所有角色;即没有简单的方法来逃避这个角色。
注意:这篇文章指出方括号不需要逃脱;但上述例子中的情况并非如此(一种情况)。 escape square brackets in PATINDEX with SQL Server