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

C# 在c中从存储过程中检索输出#,c#,sql-server,stored-procedures,output-parameter,C#,Sql Server,Stored Procedures,Output Parameter,我正在调用一个在sql server上编写的存储过程,在我的c#服务中。但我一次又一次地面临着例外: 用户代码未处理InvalidCastException:指定的强制转换无效 代码: 我的存储过程如下 这是存储过程 ALTER PROCEDURE [dbo].[pro100] @brand varchar(20), @check int output as update carlog set minex=1000 where brand=@brand; select @check=id fr

我正在调用一个在sql server上编写的存储过程,在我的c#服务中。但我一次又一次地面临着例外:

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

代码:

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

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

有人能提出可能的解决方案吗?

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

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;
}

我总是重复使用保存
输出
参数参数的变量,如下所示:-

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#强制转换为可以保存null的类型(如上所述)。我还从命令文本中删除了参数列表,因为参数正在代码中添加到参数集合中。

忽略可怜的语法意义。当强制转换无效时,请查看您尝试强制转换的值的类型,以确保它是预期的。这适用于基本上所有无效的强制转换。@NikunjVats下次请发布您的代码,而不是图像,因为当时间流逝时,图像通常会变得不可用@lazyberezovsky@NikunjVats您能否演示如何在存储过程中定义参数
check
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;
}