如果SQL Server中的过滤器值为NULL,如何在条件上过滤记录?

时间:2016-03-04 09:44:20

标签: sql-server

我想在两个条件下过滤SQL Server中的记录。我正在为此编写存储过程。

这是我的查询

// Parameters 
@carNo AS INT
@carEngineNo AS INT = null    // this is optional

Select * 
From CarLog
//Some Joins
Where 
    CarLog.car_no = carNo 
    // here I want condition, I tried this but there is some syntax error
    And CASE
            When @carEngineNo IS NOT NULL THEN CarLog.engine_no= carEngineNo 
            WHEN @carEngineNo IS NULL  THEN CarLog.engine_no = CarLog.engine_no
            END

我该怎么做?

2 个答案:

答案 0 :(得分:2)

这很简单OR

...
AND (@carEngineNo is NULL or CarLog.engine_no = @carEngineNo)

考虑将option(recompile)附加到查询中,因为实际参数集可能不同。

你的case已修复:

AND CarLog.engine_no = 
        CASE
        When @carEngineNo IS NOT NULL THEN @carEngineNo 
        WHEN @carEngineNo IS NULL THEN CarLog.engine_no
        END

备用:

AND CarLog.engine_no = IsNull(@carEngineNo, CarLog.engine_no)

答案 1 :(得分:0)

使用关键词,

isnull(@carEngineNo,-1) in (-1, CarLog.engine_no)

如果@carEngineNo为null,则它为-1,否则我们得到它。