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

Include in where clause if the value is not null

我只是 return 基于输入参数的值,如果项目描述为空,我不想将其包含在 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'.

您不能在 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)

此选项更好,因为如果变量为空,sql 服务器不需要测试实际数据。

注意 #1 如果其中一列可以为空,您将需要决定如何处理空值,因为 NULL = NULL 总是 return false .

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