I have a stored procedure with an output parameter. How do I read this value using C# code?
A Stored Procedure can have any number of output parameters. The simple logic is this — If you want to return 1 value then use 1 output parameter, for returning 5 values use 5 output parameters, for 10 use 10, and so on.
The easy way is to right-click on the procedure in Sql Server Management Studio (SSMS), select 'Execute stored procedure..." and add values for the input parameters as prompted. SSMS will then generate the code to run the procedure in a new query window, and execute it for you.
Expand the database that you want, expand Programmability, and then expand Stored Procedures. Right-click the user-defined stored procedure that you want and select Execute Stored Procedure. In the Execute Procedure dialog box, specify a value for each parameter and whether it should pass a null value.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With