简体   繁体   中英

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 ))

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.


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM