0

I am calling a stored procedure written at sql server, in my c# service. But I am again and again facing exception:

InvalidCastException was unhandled by user code: Specified cast is not valid

Code:

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

My stored procedure is as follows This is the stored proc

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

Could someone suggest the possible solution maybe?

4

2 に答える 2

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;
}
于 2013-12-01T18:52:39.160 に答える