简体   繁体   English

在存储过程调用中使用默认参数

[英]Using Default Parameter in Stored Procedure call

I have the following stored procedure 我有以下存储过程

CREATE PROCEDURE [dbo].[usp_GetData]
@foo VARCHAR (20), @bar bit = 1
AS ...

This provides the correct result when called in SSMS. 这在SSMS中调用时提供了正确的结果。

EXEC dbo.usp_GetData @foo = 'Hellow World', @bar = 0

Although when calling within a C# application as per below 虽然在C#应用程序中调用如下所示

cmd.Parameters.Add(new SqlParameter("@foo", foo)); 
cmd.Parameters.Add(new SqlParameter("@bar", 0));

& is captured by the profiler as below. &由剖析器捕获,如下所示。

exec dbo.usp_GetData @foo=N'Hello World',@bar=default

Does a parameter that overides the default have to be passed differently? 是否必须以不同方式传递超出默认值的参数?

Use 使用

cmd.Parameters.AddWithValue("@bar", 0)

This way you know you actually passing the value. 这样你就知道你实际传递了这个值。

new SqlParameter("@bar", 0) triggers the wrong overload - string parameterName, SqlDbType dbType . new SqlParameter("@bar", 0)触发错误的重载 - string parameterName, SqlDbType dbType The value ends up being not set. 该值最终未设置。

You want the one that sets the value, so it's ought to be new SqlParameter("@bar", (object)0) . 你想要一个设置值的那个,所以它应该是new SqlParameter("@bar", (object)0)

This is why AddWithValue was introduced. 这就是引入AddWithValue原因。

更好,更安全:

cmd.Parameters.Add("@bar", SqlDbType.NVarChar, 16, "bar");

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

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