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
Try this
DECLARE @productID INT = NULL
SELECT
ProductID,
ProductName,
ProductDesc
FROM
product
WHERE
ProductID = isnull(@productID,ProductID)
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.
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 )
SELECT
ProductID,
ProductName,
ProductDesc
FROM
product
WHERE
ProductID = CASE WHEN @productID IS NULL THEN ProductID ELSE @productID END
Since "" is not recognized as NULL
I used value
SELECT ProductID, ProductName,ProductDesc
FROM product
WHERE ProductID =IIF(@productID =1, ProductID, @productID )
In my code:
MyDataAdapter.SelectCommand.Parameters("@productID").Value = 1
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