[英]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.