How to use CASE statement inside a WHERE with an IN clause?
If you want an "elegant solution", you might want to consider store these values in a table that can be used in your query.
CREATE TABLE #ValidIds(
ShowListedOrSold int,
id int);
INSERT INTO #ValidIds
VALUES( 0, 1),
( 0, 2),
( 0, 5),
( 0, 6),
( 0, 10),
( 0, 11),
( 1, 1),
( 1, 5),
( 1, 6),
( 1, 10),
( 1, 11),
( 2, 2);
SELECT *
FROM table t
JOIN #ValidIds v ON t.id = v.id
AND v.ShowListedOrSold = @ShowListedOrSold;
You could solve this by using OR instead of CASE:
SELECT *
FROM table
WHERE (@showListedOrSold = 0 AND id IN (1, 2, 5, 6, 10, 11))
OR (@showListedOrSold = 1 AND id IN (1, 5, 6, 10, 11))
OR (@showListedOrSold = 2 AND id IN (2))
This starts to get rather complicated. I might recommend a join
approach:
select t.*
from table t join
(values (0, 1), (0, 2), (0, 5), (0, 6), (0, 10), (0, 11),
(1, 1), (1, 5), (1, 6), (1, 10), (1, 11),
(2, 2)
) v(slos, id)
on t.slos = @showListedOrSold and
v.id = s.id
You can easily expand this to show all rows if the variable is null
:
on (t.slos = @showListedOrSold and
v.id = s.id
) or
@showListedOrSold is null