Is it posible to use case in where in clause? Something like this:
DECLARE @Status VARCHAR(50); SET @Status='published'; SELECT * FROM Product P WHERE P.Status IN (CASE WHEN @Status='published' THEN (1,3) WHEN @Status='standby' THEN (2,5,9,6) WHEN @Status='deleted' THEN (4,5,8,10) ELSE (1,3) END)
This code gives the error : Incorrect syntax near ','.
CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.
Introduction to Oracle CASE expression You can use a CASE expression in any statement or clause that accepts a valid expression. For example, you can use the CASE expression in statements such as SELECT , UPDATE , or DELETE , and in clauses like SELECT , WHERE , HAVING , and ORDDER BY .
CASE must include the following components: WHEN , THEN , and END . ELSE is an optional component. You can make any conditional statement using any conditional operator (like WHERE ) between WHEN and THEN . This includes stringing together multiple conditional statements using AND and OR .
The SQL IN OperatorThe IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.
No you can't use case
and in
like this. But you can do
SELECT * FROM Product P WHERE @Status='published' and P.Status IN (1,3) or @Status='standby' and P.Status IN (2,5,9,6) or @Status='deleted' and P.Status IN (4,5,8,10) or P.Status IN (1,3)
BTW you can reduce that to
SELECT * FROM Product P WHERE @Status='standby' and P.Status IN (2,5,9,6) or @Status='deleted' and P.Status IN (4,5,8,10) or P.Status IN (1,3)
since or P.Status IN (1,3)
gives you also all records of @Status='published' and P.Status IN (1,3)
I realize this has been answered, but there is a slight issue with the accepted solution. It will return false positives. Easy to fix:
SELECT * FROM Products P WHERE (@Status='published' and P.Status IN (1,3)) or (@Status='standby' and P.Status IN (2,5,9,6)) or (@Status='deleted' and P.Status IN (4,5,8,10)) or (@Status not in ('published','standby','deleted') and P.Status IN (1,2))
Parentheses aren't needed (although perhaps easier to read hence why I included them).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With