views:

83

answers:

1

I have a string property that may or may not be null.

I am passing it to the SP using this call:

db.AddInParameter(InsertMessageDetailCommand, "MyParam", System.Data.DbType.String, this.myParam);

the field is defined in the SP like this:

@MyParam nvarchar(50)

How can I change the SP to allow for null values, and if param value is null insert a null into the database table later in the SP?

Thanks

+2  A: 

To declare a stored procedure parameter as optional:

@MyParam nvarchar(50) = NULL

For instance:

CREATE PROCEDURE TestProc
(
    @Param1 varchar(50) = NULL
)
AS
SELECT
    * 
FROM
    TestTable
WHERE
    ((@Param1 IS NULL) OR (col1 = @Param1))

But please be aware that this pattern, when used with many parameters can lead to incorrectly cached query plans due to 'parameter sniffing'.

Mitch Wheat
let me test, one sec....
JL
updated, missed the equals sign!
Mitch Wheat
Incorrect syntax near the keyword 'NULL'
JL
thanks , retesting....
JL
Thanks, worked like a charm.
JL
@Mitch - IIRC, parameter sniffing is less of an an issue in SQL Server 2005+, and there is also the OPTIMIZE FOR clause when problems do arise - http://blogs.msdn.com/queryoptteam/archive/2006/03/31/565991.aspx
Russ Cam
@Russ Cam: thanks, I'm aware of that. I've popsted to SO about OPTIMISE FOR in fact.
Mitch Wheat