简体   繁体   中英

SQL Server 2008 WHERE clause with CASE / WHEN and NULL value

I'm trying to write something like :

SELECT *
FROM MyTable m
WHERE m.Category = CASE WHEN @Category IS NULL THEN m.Category ELSE @Category END

Basically, I need lines where m.Category equals @Category if this one has a value ; else, I need all lines.

BUT if m.Category has NULL value, the line is NOT send back because SQL needs something lile WHERE m.Category IS NULL and not WHERE m.Category = NULL .

So, how could I modify my request to tell to SQL : "I need ALL lines if @Category is null (even lines where m.Category is null), but if @Category has a value, I just need lines where m.Category matches @Category ?

you can write it like this:

select *
from MyTable m
where @Category is null or m.Category = @Category

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