SQL select all if parameter is null else return specific item

前端 未结 6 1466
终归单人心
终归单人心 2020-12-03 05:29

Is there a way to write the following script so that it returns all products if the ProductID variable is null ? And return a specific product when the product it is not nul

6条回答
  •  生来不讨喜
    2020-12-03 06:09

    Performance is a incredible better when using CASE statement:

    SELECT ProductID, ProductName,ProductDesc 
    FROM product 
    WHERE ProductID = CASE WHEN @productID IS NULL THEN ProductID ELSE @productID END
    

    ISNULL() prevents the optimizer using an index on that column.

提交回复
热议问题