SQL select all if parameter is null else return specific item

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 )

Leave a Comment