以下のコード例では、すべての結果が 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
場合によっては、これが機能しない理由が理にかなっています。つまり、特殊文字が正しくエスケープされていません。
ただし、左クロチェットの場合、エスケープする必要があるかどうかは、キャレットの後に続くかどうか (つまり、この文字で一致するか、この文字以外のすべての文字で一致するか) によって異なります。
右クロッチの場合、右クロッチ以外のすべての文字を一致させる方法はないようです。つまり、この文字をエスケープする簡単な方法はありません。
注意: この投稿では、角括弧をエスケープする必要はないと述べています。しかし、上記の例 (の 1 つのシナリオ) ではそうではありません。 SQL Server で PATINDEX の角かっこをエスケープする