21

I have a stored procedure with an output parameter. How do I read this value using C# code?

2
  • Please post the code you have written so far. Commented Aug 8, 2010 at 9:02
  • 1
    I'd upvote this because it's a useful question, but because of lack of "I tried this" I can't do so. Commented Sep 16, 2013 at 17:37

1 Answer 1

41

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

i have another question i need to determine that output parameter is decimal(8,2) how!!!
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
I would strongly suggest to put SqlConnection and SqlCommand into using(....) { ... } blocks as a best practice
i have problem when call stroc embeded or execution nested stroc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.