Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select all if parameter is null else return specific item

Tags:

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
like image 737
nick ken Avatar asked Oct 14 '13 10:10

nick ken


2 Answers

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 )
like image 113
Harminder Avatar answered Oct 04 '22 15:10

Harminder


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

like image 25
mucio Avatar answered Oct 04 '22 15:10

mucio