I have a stored procedure with an output parameter. How do I read this value using C# code?
-
Please post the code you have written so far.Mitch Wheat– Mitch Wheat2010-08-08 09:02:22 +00:00Commented Aug 8, 2010 at 9:02
-
1I'd upvote this because it's a useful question, but because of lack of "I tried this" I can't do so.JYelton– JYelton2013-09-16 17:37:40 +00:00Commented Sep 16, 2013 at 17:37
Add a comment
|
1 Answer
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:
using (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();
}
4 Comments
shmandor
i have another question i need to determine that output parameter is decimal(8,2) how!!!
Merrimack
I am not sure I understand the question. If you are returning a decimal in the output variable you should set the SqlDbType to Decimal. If you are in fact returning a decimal you can cast like this: (decimal)cmd.Parameters[@"MyDecimal"].Value
marc_s
I would strongly suggest to put
SqlConnection and SqlCommand into using(....) { ... } blocks as a best practiceshmandor
i have problem when call stroc embeded or execution nested stroc