存储过程返回空值作为输出参数

10

我有一个 存储过程 ,在MS SQL management studio中运行良好。

但当我试图在VS中使用它时,行返回正常,但输出参数的值为 NULL

SqlCommand cmd = new SqlCommand("proc_name", conn);
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(new SqlParameter("@p_SomeVal", SqlDbType.Int));
cmd.Parameters["@p_SomeVal"].Direction = ParameterDirection.Output;

rdr = cmd.ExecuteReader();
//...process rows...

if (cmd.Parameters["@p_SomeVal"].Value != null)
SomeVal = (int)cmd.Parameters["@p_SomeVal"].Value;

cmd.ExecuteNonQuery(); 有相同的结果。

USE [db_name]
GO

DECLARE @return_value int,
    @p_SomeValue int

EXEC    @return_value = [dbo].[Proc_name]
    @p_InputVal = N'aa',
    @p_SomeValue = @p_SomeValue OUTPUT

SELECT  @p_SomeValue as N'p_SomeValue'

SELECT  'Return Value' = @return_value

GO

这个程序长什么样子?你是在VS和SSMS中运行同一个数据库吗? - Oded
4
顺便提一下,你应该针对DBNull.Value进行测试,而不是null - Oded
@Oded 我也试过了,但运气一样不好。 - SpoksST
@Oded 我添加了我所拥有的关于此过程的内容 - 我没有查看更多内容的权限。 - SpoksST
我无法理解你那里的代码 - 看起来你只是在转发参数 - 但仍然看不到Proc_name是什么样子。 - Oded
显示剩余6条评论
2个回答

26
SqlCommand cmd = new SqlCommand("proc_name", conn);
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(new SqlParameter("@p_SomeVal", SqlDbType.Int));
cmd.Parameters["@p_SomeVal"].Direction = ParameterDirection.Output;

rdr = cmd.ExecuteReader();
//...process rows...

rdr.Close();

if (cmd.Parameters["@p_SomeVal"].Value != null)
SomeVal = (int)cmd.Parameters["@p_SomeVal"].Value;

在处理行后,我添加了rdr.Close();,然后正常运作。


@Oded的解决方案很简单 :( - SpoksST
或者,如果你喜欢一行代码,你可以这样写 var SomeVal = command.Parameters["@p_SomeVal"].Value != null ? (int)command.Parameters["@p_SomeVal"].Value : default(int); - Sturla
抱歉我太匆忙了... null 和 DBNull... 你必须在这里使用以下代码:var SomeVal = command.Parameters["@p_SomeVal"].Value is DBNull ? default(int) : (int)command.Parameters["@p_SomeVal"].Value; - Sturla

3

你好,您可以检查输出是否为null,并像这样进行转换。

returnedSQLParameter.Value != DBNull.Value? (int)returnedSQLParameter.Value : 0;

由于存储过程输出 NULL 时返回的是 DBNull.value,因此出现了这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接