简体   繁体   English

如何从C#将可为空的字符串传递给SP

[英]How to pass a nullable string to an SP from C#

I have a string property that may or may not be null. 我有一个字符串属性,它可以为null或可以不为null。

I am passing it to the SP using this call: 我使用此调用将其传递给SP:

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

the field is defined in the SP like this: 该字段在SP中定义如下:

@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? 如何更改SP以允许使用null值,并且如果param值为null,则稍后在SP中将null插入数据库表中?

Thanks 谢谢

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'. 但是请注意,这种模式与许多参数一起使用时,可能会由于“参数嗅探”而导致错误地缓存查询计划。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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