mssql patindex用于]符号

时间:2018-09-04 06:58:02

标签: sql-server character symbols patindex

如何在字符类中指定]符号(MS SQL SERVER PATINDEX函数)?

'%["[]%' - for starting bracket - it works
'%["]]%' - for ending - it does not

2 个答案:

答案 0 :(得分:0)

似乎无法正确地逃避PATINDEX中的右括号()。 ]仅可以是written verbatim,但不能包含在字符集中。

但是,根据this DBA.SE question,有一些解决方法(有关完整示例,请参见链接的文章):

  1. Specify character range that contains ]. (note that this will match unwanted characters)
PATINDEX('%[[-^{}:,]%' COLLATE Latin1_General_BIN2, MyJSONString)
  1. Apply REPLACE before match.
PATINDEX('%[[' + CHAR(174) + '@]%', REPLACE(@test,']',CHAR(174)))
  1. Use PATINDEX twice: one for ], and the other for the rest of characters.
(NULLIF(PATINDEX('%[[{}:,]%', d.ResponseJSON), 0), NULLIF(PATINDEX('%]%', d.ResponseJSON), 0)))

答案 1 :(得分:0)

在测试了不同的选项之后,这似乎可以正常工作。试试看。

PATINDEX('%[^]]%', 'test[test]') +1

之所以加上“ +1”,是因为在我执行的每个测试中,它总是在结尾括号“]”之前停一个字符,从而确保捕获打开位置和关闭位置。

尝试一下,让我知道您的想法。