简体   繁体   中英

Where in case in SQL Server

If @IsPrice=0 , ProductPrice=0 will return. If not, ProductPrice > 0 will return. This is what I want, but I could not write the code exactly.

declare @Isprice bit=0

select * 
from [Product] p 
where case when @Isprice = 0 then p.ProductPrice = 0 else p.ProductPrice > 0 end

A case expression returns a value, not an SQL fragment. You could get this behavior by using some logical operators, though:

SELECT *
FROM   [Product] p 
WHERE  (@Isprice = 0  AND p.ProductPrice = 0) OR
       (@Isprice <> 0 AND p.ProductPrice > 0)

If you want to keep the CASE logic you could also consider:

SELECT *
FROM   [Product] p 
WHERE  
1 = CASE
WHEN (@Isprice = 0  AND p.ProductPrice = 0) THEN 1
WHEN (@Isprice <> 0 AND p.ProductPrice > 0) THEN 1
ELSE 0
END;

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