从c#中的存储过程中检索输出

时间:2013-12-01 17:06:12

标签: c# sql-server stored-procedures output-parameter

我在我的c#服务中调用在sql server上编写的存储过程。但我一次又一次地面临异常:

  

用户代码未处理InvalidCastException:指定的强制转换无效

代码:

public function(Data dt)
{
    con = new SqlConnection(constring);
    string brand = dt.brand;
    cmd = new SqlCommand("execute pro100 @brand, @check", con);

    SqlParameter param = new SqlParameter("@check", SqlDbType.Int);
    param.Direction = ParameterDirection.Output;
    cmd.Parameters.Add("@brand", brand);
    cmd.Parameters.Add(param);
    con.Open();
    cmd.ExecuteNonQuery();

    int result = (int)cmd.Parameters["@check"].Value; // Exception is here
    con.Close();
    return result;
}

我的存储过程如下 这是存储过程

ALTER PROCEDURE [dbo].[pro100]
@brand varchar(20), 
@check int output
as
update carlog set minex=1000 where brand=@brand;
select @check=id from carlog where brand=@brand;
return @check

有人可能建议可能的解决方案吗?

2 个答案:

答案 0 :(得分:0)

这是一个忽略异常处理的解决方案:

public function(Data dt)
{
    con = new SqlConnection(constring);

    cmd = new SqlCommand("pro100", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@brand", dt.brand);
    cmd.Parameters.Add("@check", SqlDbType.Int).Direction = ParameterDirection.Output;

    con.Open();
    cmd.ExecuteNonQuery();   
    int result = Convert.ToInt32(cmd.Parameters["@check"].Value);
    con.Close();
    return result;
}

答案 1 :(得分:0)

我总是重复使用包含output参数参数的变量,如下所示: -

public function(Data dt)
{
    con = new SqlConnection(constring);
    string brand = dt.brand;
    cmd = new SqlCommand("execute pro100", con);

    SqlParameter param = new SqlParameter("@check", SqlDbType.Int);
    param.Direction = ParameterDirection.Output;
    cmd.Parameters.Add("@brand", brand);
    cmd.Parameters.Add(param);
    con.Open();
    cmd.ExecuteNonQuery();

    int? result = (int?)param.Value; // Exception was here
    con.Close();
    return result;
}

但是您可能还需要处理从存储过程返回的null值 - 从不返回null - 或者通过将C#转换为可以保存空值的类型(如上所述) )。我还从命令文本中删除了参数列表 - 因为参数正在代码中添加到参数集合中。

相关问题