Please note that I want to find special character in string other that what i specify.
DECLARE @Temp1 NVARCHAR(100)
SET @Temp1 ='Rajesh[sdf]'
SELECT PATINDEX('%[^0-9A-Za-z .&()[[,''-]%',@Temp1)
After a long finding I got for allowing left square bracket we have to put two times [ i.e [[
But this is not the case for right bracket
The Expression PATINDEX(‘%[^0-9A-Za-z .&()[[],”-]%’,@Temp1) does not give the proper result expected.
DECLARE @Temp1 NVARCHAR(100)
SET @Temp1 ='Rajesh[sdf]'
SELECT PATINDEX('%[^0-9a-z .&()[[],''-]%',@Temp1)
Above code returns patindex 0 as I have removed uppercase . It should return 1 For match for ‘R’. So what is right match for right bracket.
Per this link, it looks like
[[is not the escape for[but rather[[]. In other words, a left square bracket within a left-right square bracket pair.This being the case, your
PATINDEXshould be as follows.Notice the additional
]since the first]closes out the[]pair to match[.EDIT #1:
What if you were to try something like this? What we’re doing is first replacing the bothersome
[]characters with()and then doing your search for special characters not in your list.Unfortunately, I can’t test this at this time because I don’t have a working copy of SQL Server right this second. I will try to test in a bit once I get one installed.
EDIT #2:
Now that I’ve been able to test, I’ve confirmed this as a possible solution.
There were several challenges that needed to be overcome.
COLLATEto get around this. Note that I used theBINcollation because even theCScollation didn’t behave as expected. This fixed the problem where removingA-Zstill wouldn’t match onR.-character from the originalPATINDEXexpression was not working correctly. This is probably because it is a special character in the expression (i.e. “through” ina-z). I tried escaping it like--and while this worked, my additional test case of a+was broken. I found this really odd, but in the end decided it might be easier to just substitute-with another character I knew I was going to reject (.).REPLACEfunctions reduces the complexity of thePATINDEX(and makes it actually work) by removing the offending special characters from the expression completely. Assuming you’ll always have at least one character you’re rejecting in thePATINDEX, using theseREPLACEexpressions should be a workable solution. In theory it will slow things down a bit, but that’s something that will just have to be tested in real-life to see if it matters any.I know that this solution works as I’ve been able to test it. Just needed a little bit of time to get SQL Server Express Edition up and running!