Search code examples
sqlsql-servert-sqlcase

How do I extract data within parentheses from a table with different values?


Im trying to extract data within a column that contains IDs and characters that contain IDs within parentheses. It looks somewhat like this (Btw, there will only be one set of parentheses if they happen to exist within a row):

Col1
Mark(1234)
6789
VZ(X678)
ASD(5677)qwe
Ideal Result
1234
6789
X678
5677

This is what I have so far but its returning an error: 'Invalid length parameter passed to the LEFT or SUBSTRING function.'

SELECT DISTINCT col1,
CASE WHEN col1 like '%(%' then
SUBSTRING (col1,
            CHARINDEX('%(%', col1) + 1,
            CHARINDEX('%)%', col1) - CHARINDEX('%(%', col1) - 1)
            else col1 end
from MyTable B; 

Solution

  • @martin Smith Thanks for pointing out the used of the wildcards. I changed my code to this and its doing what I needed it to do! Using the case when expression to look for the parentheses regardless of location so I kept the % wildcard there but took it out in the CHARINDEX as you mentioned:

    SELECT DISTINCT col1,
    CASE WHEN col1 like '%(%' then
    SUBSTRING (col1,
            CHARINDEX('(', col1) + 1,
            CHARINDEX(')', col1) - CHARINDEX('(', col1) - 1)
            else col1 end
    from MyTable B;