0

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 2

1

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

Comments

0

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();

Comments

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.