SQL use CASE statement in WHERE IN clause

前端 未结 7 1492
南方客
南方客 2020-12-06 00:17

Is it posible to use case in where in clause? Something like this:

 DECLARE @Status VARCHAR(50);
 SET @Status=\'published\';

 SELECT * FRO         


        
7条回答
  •  长情又很酷
    2020-12-06 00:27

    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))
    
    • SQL Fiddle Demo

    Parentheses aren't needed (although perhaps easier to read hence why I included them).

提交回复
热议问题