Here's a safe but slow solution for SQL 2008
BEGIN -- setup DECLARE @tbl TABLE ( [contentid] INT ,[group] VARCHAR(MAX) ) INSERT INTO @tbl VALUES (1, 'c,d') ,(2, 'a,c') ,(3, 'd') -- send your request as simple xml DECLARE @param XML SET @param = '<g>a</g><g>c</g>' -- query SELECT DISTINCT contentid FROM @tbl t INNER JOIN @param.nodes('/g') AS t2(g) ON ',' + t.[group] + ',' LIKE '%,' + t2.g.value('.', 'varchar(max)') + ',%' END
You simply pass your request as an XML fragment instead of a comma separated list.
If your group names are single characters, or you can be sure that the names are not subsets of each other's characters (i.e.: GroupA, GroupAB), then the query can be optimized.
ON t.[group] LIKE '%' + t2.g.value('.', 'varchar(max)') + '%'
If you use RDBMS without the ability to parse XML, you will have to use a string that splits your query into a temporary table and works this way.
You really shouldn't use comma separated values ββinside your columns. It would be much better if the [group] column contained only one value and you had duplicate entries with a UNIQUE constraint for the composite (contentid, group).
source share