简体   繁体   中英

SQL Server, Case When then in Where clause

I have a boolean that can be null, 1, or 0. If it is 1 I need it to return only rows with Status Id value of 4, if it is 0 then anything but 4, and if it is null then all values.

I was hoping to do something like below but it is not possible, does anyone know the correct way to write this in the WHERE clause?

(O.Order_Status_Id = CASE WHEN @Include_Submitted = 1
                                    THEN 4
                                WHEN @Include_Submitted = 0
                                    THEN NOT 4
                                END 
                     OR @Include_Submitted IS NULL)

Instead of a case expression use AND and OR .

(O.Order_Status_Id = 4 AND @Include_Submitted = 1)
OR (O.Order_Status_Id <> 4 AND @Include_Submitted = 0)
OR (@Include_Submitted IS NULL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM