1

在下面的代码示例中,所有结果都应返回 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

在某些情况下,为什么这不起作用是有道理的。即特殊字符没有被正确转义的地方。

然而,对于左 crotchet,它是否需要转义取决于它是否跟在插入符号之后(即我们是匹配这个字符,还是匹配除这个字符之外的所有字符)。

对于右四分法,似乎没有办法匹配除右四分法以外的所有字符;即没有简单的方法来逃避这个角色。

注意:这篇文章指出方括号不需要转义;但在上述示例中(一种情况)并非如此。 使用 SQL Server 转义 PATINDEX 中的方括号

4

0 回答 0