I am writing C# method to call SP with parameters.
It has input parameters ,which + their values I add using cmd.Parameters.AddWithValue
But I also need output parameter...How do I add it after I added all inputs with cmd.Parameters.AddWithValue
2 Answers
check SqlParameterCollection.AddWithValue Method return type, it is SqlParameter you can set the Direction of it as one of ParameterDirection
var parameter = cmd.Parameters.AddWithValue(.....
parameter.Direction = ParameterDirection.Output;
Comments
I assume you use ADO.NET? If so, the SqlParameter class has the property "Direction". Set direction to output and after the query has executed you read the value from that parameter.
Something like this:
SqlCommand cmd = new SqlCommand("MyStoredProcedure", cn);
cmd.CommandType=CommandType.StoredProcedure;
SqlParameter parm=new SqlParameter("@pkid",SqlDbType.Int);
parm.Value=1;
parm.Direction =ParameterDirection.Input ;
cmd.Parameters.Add(parm);
SqlParameter parm2=new SqlParameter("@ProductName",SqlDbType.VarChar);
parm2.Size=50;
parm2.Direction=ParameterDirection.Output; // This is important!
cmd.Parameters.Add(parm2);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
// Print the output value
Console.WriteLine(cmd.Parameters["@ProductName"].Value);
Console.ReadLine();