How to use CASE statement inside a WHERE with an IN clause?

Ang*_*ker 6 sql sql-server sql-server-2016

I am trying to do the following (pseudocode since it doesn't compile):

declare showListedOrSold  int = 1 -- get value from config table

select *
from table
where CASE WHEN @showListedOrSold = 0 THEN id IN (1, 2, 5, 6, 10, 11) 
             WHEN @showListedOrSold = 1 THEN id IN (1, 5, 6, 10, 11) 
             WHEN @showListedOrSold = 2 THEN id IN (2) 
      END
Run Code Online (Sandbox Code Playgroud)

Basically depending on value of showListedOrSold, it should bring back certain id values.

The statement is not liking the IN clause. What is the correct syntax for this use case?

Lui*_*res 7

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;
Run Code Online (Sandbox Code Playgroud)


Gre*_*ers 6

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))
Run Code Online (Sandbox Code Playgroud)


Gor*_*off 5

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)