简体   繁体   English

具有CASE / WHEN和NULL值的SQL Server 2008 WHERE子句

[英]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 ; 基本上,如果此行具有值,则需要m.Category等于@Category行; 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 . 但是如果m.Category具有NULL值,则不会发送该行,因为SQL需要一些条件WHERE m.Category IS NULL而不是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 ? 因此,我该如何修改告诉SQL的请求:“如果@Category为空(即使m.Category为null的行),我也需要所有行,但是如果@Category有值,我只需要m.Category符合@Category吗?

you can write it like this: 您可以这样写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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