Environment: Sql Server 2008
have rows of a column that contains comma separated values.
what to get the row even if a single product exists in that csv.
this is how i can do it but was just wondering if another way to write it?
SELECT * FROM REWARDS
WHERE ProductCsv like '%banana%'
or ProductCsv like '%strawberry%'
or ProductCsv like '%orange%'
Your current query doesn’t seem to accurately capture the results you want. What if we have a row like this:
Should this match your query or not? I think this would be more accurate:
If you’re just trying to find one item, this is probably much more efficient:
You probably want to use a split function. For example:
So now you can say:
Or more simply:
The XML approach is a little brittle depending on the kinds of strings can be stored in the table, but there are many alternatives (including passing in your set via a TVP instead of as a list or separate values). For some much deeper background on split functions see these blog posts:
http://www.sqlperformance.com/2012/07/t-sql-queries/split-strings
http://www.sqlperformance.com/2012/08/t-sql-queries/splitting-strings-follow-up
http://www.sqlperformance.com/2012/08/t-sql-queries/splitting-strings-now-with-less-t-sql
That all said, I don’t know if this is any better than what you have now.