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 null. What I have so far:
DECLARE @productID INT = NULL
SELECT
    ProductID,
    ProductName,
    ProductDesc 
FROM
    product 
WHERE
    ProductID = @productID
                Use case statement:
SELECT ProductID, ProductName,ProductDesc 
FROM product 
WHERE ProductID = CASE WHEN @productID IS NULL THEN ProductID ELSE @productID END
Or IIF() function if you’re using SQL Server 2012:
SELECT ProductID, ProductName,ProductDesc 
FROM product 
WHERE ProductID =IIF(@productID IS NULL, ProductID, @productID )
                        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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With