How to specify ] symbol inside character class (MS SQL SERVER PATINDEX function)?
'%["[]%' - for starting bracket - it works
'%["]]%' - for ending - it does not
How to specify ] symbol inside character class (MS SQL SERVER PATINDEX function)?
'%["[]%' - for starting bracket - it works
'%["]]%' - for ending - it does not
Looks like there is no way to properly escape closing bracket (]) in PATINDEX. ] alone can be written verbatim, but cannot be included in the character set.
However, according to this DBA.SE question, there are some workaround (see the linked article for the full example):
PATINDEX('%[[-^{}:,]%' COLLATE Latin1_General_BIN2, MyJSONString)
PATINDEX('%[[' + CHAR(174) + '@]%', REPLACE(@test,']',CHAR(174)))
(NULLIF(PATINDEX('%[[{}:,]%', d.ResponseJSON), 0), NULLIF(PATINDEX('%]%', d.ResponseJSON), 0)))
After testing different options, this seemed to work as expected. Give it a try.
PATINDEX('%[^]]%', 'test[test]') +1
The "+1" is added because in every test I performed it always stopped one character before the ending bracket "]", this makes sure to capture open and closing positions.
Give it a try, let me know what you think.