0

I have a SQL Column with the following values

ReportID
--------
19
19,20,21
20,19,21
20,21,19
119,21
1191,21

I need to match the the rows which have 19 as a value (i.e. reject last two rows)

Is there a better way to do this than the query used below ? (Using combined regex)

My Query:

SELECT * 
FROM [StoreBI_Validation].[dbo].[PortalNotifications]
WHERE ReportID like '%,19,%' 
   or ReportID like '19' 
   or ReportID like '19,%' 
   or ReportID like '%,19'
2
  • 2
    The correct solution is to not store comma separated values in a column. If you properly normalize your data you wouldn't have that problem. A quick workaround is to store a leading and trailing comma, e.g. ,20,19,21, then you using %,19,% is enough Commented Mar 31, 2016 at 7:40
  • If you normalize your data, not only would you not have this problem, but your queries would work significantly faster as you could use an index on the reportID column. There's no way of using an index with your current query. Commented Mar 31, 2016 at 8:12

2 Answers 2

4

Try this :

SELECT * 
FROM Test
WHERE ','+ReportID+',' like '%,19,%'

SQL Fiddle

Or this :

SELECT DISTINCT reportid
FROM (
    SELECT A.ReportID
        ,Split.a.value('.', 'VARCHAR(100)') AS Data
    FROM (
        SELECT ReportID
            ,CAST('<M>' + REPLACE(ReportID, ',', '</M><M>') + '</M>' AS XML) AS Data
        FROM Test
        ) AS A
    CROSS APPLY Data.nodes('/M') AS Split(a)
    ) B
WHERE Data = '19';
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT * 
FROM [StoreBI_Validation].[dbo].[PortalNotifications]
WHERE CHARINDEX(',19,',ReportID)>0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.