Tsql T-SQL WHERE子句-在空列上将列与自身进行比较失败

Tsql T-SQL WHERE子句-在空列上将列与自身进行比较失败,tsql,null,where-clause,Tsql,Null,Where Clause,我通常使用这样的构造将筛选器应用于列: CREATE TABLE test(a int NOT NULL, b int NULL) --insert some data INSERT INTO test(a,b) values (1,1) INSERT INTO test(a,b) values (1,NULL) declare @a int declare @b int set @a = 1 --@b is null at this time select * from test wh

我通常使用这样的构造将筛选器应用于列:

CREATE TABLE test(a int NOT NULL, b int NULL)
--insert some data
INSERT INTO test(a,b) values (1,1)
INSERT INTO test(a,b) values (1,NULL)

declare @a int
declare @b int
set @a = 1
--@b is null at this time

select * from test
  where a = @a
    and b = isnull(@b,b)
这仅选择第一行


例如,如果这是一个存储过程,参数
@b
为null,我可以在
where
子句中指定它的值来“启用”它,并指定
null
值来选择其中的b=b,这对每一列都是真的,但是如果
b
列中有
null
值,它不会被选中。有没有一个标准的方法来处理这个问题?那么,在上面的示例查询中,即使
b
列具有空值,我应该使用什么来选择所有行呢?

要检查空值,您需要在
b为空时执行此操作

您可以根据需要更改查询-

select * from test
  where a = @a
    and b = isnull(@b,b)
    or (@b is null and b is null)

谢谢,但是如果@b为NULL,这就行了,但是如果@a=1,@b=1,则查询应该只返回第一行(使用您的修复程序,它将返回两行)OK,将其更改为select*from test,其中a=@a和(b=isnull(@b,b)或(b为NULL,@b为NULL))就成功了!谢谢again@Axarydax-啊。。来得正是时候。在我编辑之前,你已经得到了答案。