I would like to create a stored proc that has an optional parameter in the WHERE part of the proc. My C# code can pass in null or a valid product id for this proc. Here it is:
declare @ProductID int
set @ProductID = null
select
*
from
Products
where
Name like '%Hasbro%'
if @ProductID is not null
begin
and ProductID = @ProductID
end
This code doesn't work. If the product id is null, I want it to only look for products with the name 'Hasbro' in it. If the product id is not null, I want it to look for products with the name 'Hasbro' in it and for matching product ids.
Thanks!
UPDATE:
Here is the working code. Thank you everyone for helping me get this!
declare @ProductID int
set @ProductID = null
select
*
from
Products
where
Name like '%Hasbro%'
and (( @ProductID is null ) or ( @ProductID is not null and ProductID = @ProductID ))
This should work also...
select
*
from
Products
where
Name like '%Hasbro%' and
(
( @ProductID is null ) or
( @ProductID is not null and ProductID = @ProductID )
)
A simpler way would be to use ISNULL
where
Name like '%Hasbro%'
and ProductID = ISNULL(@ProductID, ProductID)
This way, if @ProductID
is omitted (ie, it's NULL
in the stored procedure call), then you fall back on the original value and essentially it degrades to WHERE Name like '%Hasbro%' and ProductID = ProductID
- the second part of that is always going to be true.
Though according to the code you've got posted, it's not a stored procedure at all right now. Just so you know, you don't DECLARE
parameters like that in SQL Server, your stored procedure declaration would look like:
CREATE PROCEDURE [dbo].[YourStoredProcName]
@ProductID = NULL
AS
BEGIN
-- stuff goes here
END
And then if the stored procedure is called as just EXEC YourStoredProcName
, then @ProductID
will be NULL
and that ISNULL()
call will work a treat.
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