在WHERE子句中显示NULL值

时间:2019-02-24 03:34:53

标签: sql sql-server tsql

我整理了以下示例,以说明我要做什么。

我正在尝试在@FeatureID为NULL时在查询中,然后返回#Temp表中该ClientID的所有记录。例如,如果@FeatureID包含1,则返回1记录和NULL记录。

我的where子句哪里出错了?

CREATE TABLE #Temp
(
    ClientID int,
    FeatureID int
)

Insert into #Temp
(
    ClientID,
    FeatureID
)
SELECT
    1,
    1
UNION
SELECT
    1,
    2
UNION
SELECT
    1,
    3
UNION
SELECT
    1,
    NULL


Declare @ClientID int = 1
Declare @FeatureID int = NULL

--should return all 4 records
select * from #Temp 
where ClientID = 1 and 
FeatureID = IIF(@FeatureID IS NULL, FeatureID, @FeatureID)

Set @ClientID = 1
Set @FeatureID = 1

--should return the 1,1 record and the 1,NULL record
select * from #Temp 
where ClientID = 1 and 
FeatureID = IIF(@FeatureID IS NULL, FeatureID, @FeatureID)

drop table #Temp

3 个答案:

答案 0 :(得分:2)

另一种可能更简单的表达方式:

select * from #Temp 
where ClientID = 1 and 
(ISNULL(@FeatureID, FeatureID) = FeatureID or FeatureID is NULL)

如果@FeatureID为空,则FeatureID = FeatureID始终为真。否则,它将检查@FeatureID = FeatureID

它将始终返回FeatureID为空的行。

答案 1 :(得分:1)

您实际上正在尝试在不起作用的where子句中比较NULL = NULL。 NULL不等于另一个NULL。

对于第一个查询,您只需要在@FeatureID不为null时比较功能ID列。这可以通过测试变量并使用OR条件来实现。

--should return all 4 records
select * from #Temp 
where ClientID = 1 and 
(@FeatureID IS NULL OR FeatureID = @FeatureID)

在第二个查询中,您需要将功能ID列与@FeatureID和NULL进行比较,以获取两行。

--should return the 1,1 record and the 1,NULL record
select * from #Temp 
where ClientID = 1 and 
(@FeatureID IS NOT NULL AND (FeatureID IS NULL OR FeatureID=@FeatureID))

要在单个查询中处理这两种情况,请使用两个由OR连接的条件,这些条件基于变量是否为null分支。

select * from #Temp 
where ClientID = 1 and 
    (
        @FeatureID IS NULL 
        OR (@FeatureID IS NOT NULL AND (FeatureID IS NULL OR FeatureID=@FeatureID))
    )

答案 2 :(得分:1)

如果您想将它们组合在一起,那么应该可以:

select * from #Temp 
where ClientID = 1 and 
(@FeatureID is null
or
(@FeatureID is not null 
    and (FeatureID is null or FeatureID=@FeatureID)))

这将在@FeatureID = null时选择所有记录,并在{(1, null), (1, 1)}时返回2个结果@FeatureID = 1