Click here to Skip to main content
15,884,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I need a query to substring from the string

TableName : TestTable

ErrorCode
@TestError1(error)
@TestError2[Info]

From ErrorCode column i need to extract TestErro1 and TestError2 here my CHARINDEX will be either '(' or '['.

I have written below query.

SQL
SELECT SUBSTRING(ErrorCode, CHARINDEX ('@', ErrorCode, 1)+1, CHARINDEX ('(', ErrorCode, 1)-CHARINDEX ('@', ErrorCode, 1)-1) FROM TestTable
Posted
Comments
Mohibur Rashid 25-May-15 3:35am    
What SQL Server are you using?
RS.Ratheesh 25-May-15 3:36am    
SQLServer 2014
RossMW 25-May-15 3:39am    
I suggest add a where clause to filter just the records with '(' and union all with a seperate query olong the same lines with the [ instead.

This assumes there is only either a ( or [ in the fields.

There may be a better way but unfortunately I do not have SQL handy to test

Modified the answer. This can also be acheived via PatIndex. See below working example

SQL
DECLARE @TBL TABLE
(
	DATA VARCHAR(100)
)

INSERT INTO @TBL(DATA)
SELECT '@TestError1(error)'
UNION ALL
SELECT '@TestError2[Info]'
UNION ALL
SELECT '@TestErr[Info]'
UNION ALL
SELECT '@TestErrorABCD1234(Info)'


select *, SUBSTRING(Data, PATINDEX('@%[Aa-Zz]%[(,\[]%', DATA )+1, PATINDEX('%[(,\[]%', DATA )-2)
FROM	@TBL	
 
Share this answer
 
v3
Comments
Thava Rajan 25-May-15 4:33am    
it is for management studio not for TSQL
_Asif_ 25-May-15 5:50am    
You are right! Because of Limited support of reg Exp in PatIndex i got confisued and assumed this might have improved in 2014 which is not the case unfortunately :)
Thava Rajan 25-May-15 6:32am    
this one better than the previous one
I wouldn't do this in SQL - it's string handling is basic at best. And it doesn't handle multiple "index of" type operations well.

But:
SQL
SELECT SUBSTRING(ErrorCode,
                 CHARINDEX ('@', ErrorCode, 1)+1,
                 (CHARINDEX ('(', ErrorCode, 1) + CHARINDEX ('[', ErrorCode, 1)) - CHARINDEX ('@', ErrorCode, 1) - 1)
FROM TestTable
Should do it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900