如果值不为null,则包含在where子句中

时间:2015-05-05 08:32:21

标签: sql-server stored-procedures sql-server-2012

我只是根据输入的参数返回值,如果项目描述为null,我不想在where子句中包含它。

与项目描述一样,所有其他情况都相同。

ALTER Procedure [dbo].[WP_GetItems] 
    @IsActive     bit,
    @OrderMode    bit,
    @OrderBy      varchar(75),
    @Description  varchar(250),
    @DateFrom     datetime,
    @DateTo       datetime,
    @PriceFrom    float,
    @PriceTo      float
as
Begin 
    Select ItemID, ItemPartNumber, ItemDescription, CreatedDate, InitialPrice from Items where IsActive = @IsActive
    CASE
        WHEN @Description IS NOT NULL THEN AND ItemDescription LIKE '%' + @Description + '%' 
        WHEN @PriceFrom IS NOT NULL THEN AND InitialPrice >= @Price
        WHEN @PriceTo IS NOT NULL THEN AND InitialPrice <= @Price
    END 
    order by
    CASE WHEN @OrderBy='ItemDescription' AND @OrderMode = 0 THEN ItemDescription END ASC,
    CASE WHEN @OrderBy='ItemDescription' AND @OrderMode = 1 THEN ItemDescription END DESC,
    CASE WHEN @OrderBy='ItemPartNumber' AND @OrderMode = 0 THEN ItemPartNumber END ASC,
    CASE WHEN @OrderBy='ItemPartNumber' AND @OrderMode = 1 THEN ItemPartNumber END DESC,
    CASE WHEN @OrderBy='CreatedDate' AND @OrderMode = 0 THEN CreatedDate END ASC,
    CASE WHEN @OrderBy='CreatedDate' AND @OrderMode = 1 THEN CreatedDate END DESC,
    CASE WHEN @OrderBy='InitialPrice' AND @OrderMode = 0 THEN InitialPrice END ASC,
    CASE WHEN @OrderBy='InitialPrice' AND @OrderMode = 1 THEN InitialPrice END DESC
End

但执行此查询时出错。 Incorrect syntax near the keyword 'CASE'.

1 个答案:

答案 0 :(得分:0)

您不能在CASE中使用AND部分。 试试这个:

WHERE IsActive = @IsActive
AND ItemDescription LIKE CASE WHEN @Description IS NOT NULL THEN '%' + @Description + '%' END
AND InitialPrice >= CASE WHEN @PriceFrom IS NOT NULL THEN @Price ELSE InitialPrice END
AND InitialPrice <= CASE WHEN @PriceTo IS NOT NULL THEN @Price ELSE InitialPrice END

评论中Louaan建议的另一个选项是:

AND (@Description IS NULL OR ItemDescription LIKE '%'+ @Description +'%')
AND (@PriceFrom IS NULL OR InitialPrice >= @PriceFrom)
AND (@PriceTo IS NULL OR InitialPrice <= @PriceTo)

这个选项更好,因为如果变量为null,则不需要sql server来测试实际数据。

注意#1 如果其中一列可以为空,则需要决定如何处理空值,因为NULL = NULL始终返回false。

注意#2 您可能希望在此存储过程中包含重新编译提示以提高性能。 read this article to find out why