SQL select all if parameter is null else return specific item

前端 未结 6 1458
终归单人心
终归单人心 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:25

    Why not just:

    DECLARE @productID INT = NULL
    
    SELECT ProductID, ProductName,ProductDesc 
    FROM   product 
    WHERE  ProductID = @productID
    OR     @productID IS NULL;
    

    Here a demo in SQLFiddle with NULL and a value for @productID

提交回复
热议问题