October 4, 2011 at 7:55 am
Hi all,
How can I find the character position of the first instance of the character [ in a text string. The following doesn't work:
PATINDEX('%[%',mytextfield)
although it does work for the ] character.
Any help greatly appreciated. (I appreciated this is probably to do with the [] wildcard functionality)
rgds - Jason
October 4, 2011 at 1:09 pm
Since [ is a meta-character in wildcard expressions, you'll need to wrap it with another set of brackets:
SELECT PATINDEX('%[[]%',mytextfield)
October 5, 2011 at 1:11 am
Thanks Lutz. Appreciate the help. - you helped where google and BOL etc. failed!
Jason
----
October 5, 2011 at 1:36 pm
As usual, google will return some helpful info as long as you know the "magic spell".
in this case, "patindex escape" would have provided a number of helpful links. 😉
I agree regarding BOL though. The description provided for PATINDEX is kinda weak regarding the handling of meta-characters.
April 21, 2014 at 6:57 pm
LutzM (10/4/2011)
Since [ is a meta-character in wildcard expressions, you'll need to wrap it with another set of brackets:
SELECT PATINDEX('%[[]%',mytextfield)
Interestingly, that same pattern doesn't work for the closing square bracket (I'm on 2012).
Works:
DECLARE @strPattern nvarchar(10)
SELECT @strPattern = '%[[]%'
SELECT '123]456', PATINDEX(@strPattern, '123[456')
Doesn't work:
DECLARE @strPattern nvarchar(10)
SELECT @strPattern = '%[]]%'
SELECT '123]456', PATINDEX(@strPattern, '123]456')
April 22, 2014 at 1:24 am
You are better off using the CHARINDEX function, and CHAR or NCHAR functions when dealing with special characters.
😎
DECLARE @TEST_STR NVARCHAR(128) = N'ASDFGHJ[QWER';
SELECT CHARINDEX(NCHAR(91),@TEST_STR) AS POS
Result
POS
----
8
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply