I need to alter a query to do something like this (following is generic pseudo-code):
if (tag list contains all tags in the database) {
select every product regardless of tag, even products with null tag
}
else { //tag list is only a few tags long
select only the products that have a tag in the tag list
}
I have tried doing stuff like this, but it doesn't work:
SELECT p.Id
FROM Tags t
JOIN Products p ON p.TagId = t.Id
WHERE ((EXISTS(select Id from Tags EXCEPT select item from dbo.SplitString(@tagList,',')) AND p.TagId in (select item from dbo.SplitString(@tagList,',')))
OR (p.TagId in (select item from dbo.SplitString(@tagList,',')) or p.TagId is null))
This will take place inside of a large query with a large WHERE clause, so putting two slightly different queries in an IF ELSE statement is not ideal.
What should I do to get this working?
@tagList? And why do you use a scalar variable rather than a table? Would it not be inefficient to "fill" a scalar variable with all possible tag values in order to "select everything"? Typically we use special "flag" values (usually NULL) to allow the query to ignore a filter and include everything. Suggest you give Erland's entire website a look but esp. the discussion of dynamic search conditionsselect * from Tagswould list all of the Tags in the database.