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…