Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run the stored procedure that has OUTPUT parameter from C#?

Tags:

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

like image 262
shmandor Avatar asked Aug 08 '10 08:08

shmandor


People also ask

Can stored procedure have output parameter?

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.

How do you call SP with output parameters?

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.

How do you execute a parameterized stored procedure?

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.


1 Answers

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(); } 
like image 117
Merrimack Avatar answered Sep 19 '22 01:09

Merrimack