通过过程调用时 ADO.NET 中的整数输出参数空问题
Integer out parameter null issue in ADO.NET while calling through procedure
当我尝试从 SQL 服务器存储过程(INT
类型)获取输出值时遇到一个问题,然后我得到 NULL 值 ☹。
存储过程如下:
CREATE PROCEDURE dbo.NULLISSUE
@input VARCHAR(10),
@output INT = 0 OUTPUT
AS
BEGIN
IF @input >= '1'
BEGIN
SET @output = @output + 1
RETURN(0)
END
END
这是 .NET 代码:
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.NULLISSUE";
command.Parameters.Clear();
command.Parameters.AddWithValue("@input", "1");
command.Parameters.AddWithValue("@output", SqlDbType.Int);
command.Parameters["@output"].Value = 0;
command.Parameters["@output"].Direction = ParameterDirection.Output;
command.CommandTimeout = 3000;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Console.WriteLine(command.Parameters["@output"].Value);
//null value ?
Console.ReadLine();
}
}
我通过在过程中执行 ISNULL(@output, 0)
来修复,但不确定为什么它可以在 .NET 端完成以及为什么 ADO.NET 而不是 passing/setting/initializing OUTPUT 参数 = 0。
提前致谢。
@output
必须是 ParameterDirection.InputOutput
如果你想让它使用客户端设置的初始值。
目前,由于它是 ParameterDirection.Output
,该值被忽略,它在过程中默认为 NULL
,NULL + anything
导致 NULL
。
当我尝试从 SQL 服务器存储过程(INT
类型)获取输出值时遇到一个问题,然后我得到 NULL 值 ☹。
存储过程如下:
CREATE PROCEDURE dbo.NULLISSUE
@input VARCHAR(10),
@output INT = 0 OUTPUT
AS
BEGIN
IF @input >= '1'
BEGIN
SET @output = @output + 1
RETURN(0)
END
END
这是 .NET 代码:
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.NULLISSUE";
command.Parameters.Clear();
command.Parameters.AddWithValue("@input", "1");
command.Parameters.AddWithValue("@output", SqlDbType.Int);
command.Parameters["@output"].Value = 0;
command.Parameters["@output"].Direction = ParameterDirection.Output;
command.CommandTimeout = 3000;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Console.WriteLine(command.Parameters["@output"].Value);
//null value ?
Console.ReadLine();
}
}
我通过在过程中执行 ISNULL(@output, 0)
来修复,但不确定为什么它可以在 .NET 端完成以及为什么 ADO.NET 而不是 passing/setting/initializing OUTPUT 参数 = 0。
提前致谢。
@output
必须是 ParameterDirection.InputOutput
如果你想让它使用客户端设置的初始值。
目前,由于它是 ParameterDirection.Output
,该值被忽略,它在过程中默认为 NULL
,NULL + anything
导致 NULL
。