SQL其中Column1 = Column1只返回非空值

bla*_*ist 2 sql where-clause sql-server-2008

我正在研究一个更大的问题,但已经缩小到这个范围,以便更容易提出这个问题.

以下查询:

Select * from User where Country = Country 
Run Code Online (Sandbox Code Playgroud)

只返回Country不为null的行.我希望如果Column1为null,它将返回它,因为NULL = NULL.

关于为什么这不符合我的预期的任何输入?

编辑:

我想这样做:

Select * from User where Country = coalesce(@Country, Country)
Run Code Online (Sandbox Code Playgroud)

如果我的变量@Country为null,我希望它能拉出所有内容.

Mar*_*ith 5

SQL使用三个值逻辑(true,false,unknown)和比较,以NULL(除与测试IS [NOT] NULL运营商)作为评价unknowntrue只要会话选项ANSI_NULLS上.

对于要从​​查询返回的行,该WHERE子句需要求值true.

在您编辑后,您可以使用

Select * 
from User 
where @Country is null or Country = @Country
option (recompile)
Run Code Online (Sandbox Code Playgroud)

要返回所有行@country is null.虽然可能更好的只是将这些分解为2个案例以避免重新编译惩罚.

IF @Country is null
Select * 
from User 
ELSE
Select * 
from User 
Where Country = @Country
Run Code Online (Sandbox Code Playgroud)