Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Include An Optional Null Parameter In SQL Server

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 ))
like image 248
Halcyon Avatar asked Feb 23 '23 18:02

Halcyon


2 Answers

This should work also...

select
    *
from
    Products
where
    Name like '%Hasbro%' and
    (
      ( @ProductID is null ) or
      ( @ProductID is not null and ProductID = @ProductID ) 
    )
like image 108
Dave Kjaer Avatar answered Feb 26 '23 08:02

Dave Kjaer


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.


edit: except this won't work for a nullable column, which in this case apparently it is. For any non-nullable column, this is probably the simplest solution.
like image 37
Daniel DiPaolo Avatar answered Feb 26 '23 08:02

Daniel DiPaolo