Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CASE Statement inside IN Clause

Is is possible to use a CASE statement inside an IN clause?

This is a simplified version of what I have been trying to get to compile correctly:

SELECT * FROM MyTable 
WHERE StatusID IN (
CASE WHEN @StatusID = 99 THEN (5, 11, 13)
ELSE (@StatusID) END )

Thanks!

like image 927
crjunk Avatar asked Jun 27 '12 17:06

crjunk


People also ask

Can we use CASE statement in FROM clause?

No, you can't pick a table to query using a CASE statement. CASE statements only go within expressions, such as for a column's value or as part of your WHERE expression.

Can we use CASE inside CASE in SQL?

CASE can be nested in another CASE as well as in another IF…ELSE statement. In addition to SELECT, CASE can be used with another SQL clause like UPDATE, ORDER BY.

Can we add CASE statement in where clause in SQL?

We can use a case statement in Where, Order by and Group by clause.


1 Answers

No. Instead, you can put it outside

SELECT *
FROM MyTable
WHERE 1 = (CASE WHEN @StatusID = 99 and StatusId in (5, 11, 13) then 1
                WHEN coalesce(@StatusId, 0) <> 99 and StatusId in (@StatusID) then 1
                ELSE 0
           END)

You can also write this without the case statement.

Another option is dynamic SQL, where you actually create a string with the SQL statement and then execute it. However, dynamic SQL seems like overkill in this case.

like image 52
Gordon Linoff Avatar answered Oct 15 '22 02:10

Gordon Linoff