hmd hmd - 1 year ago 173
ASP.NET (C#) Question

Run stored procedure in C#, pass parameters and capture the output result

This is a simple task that I want to acheive but ASP.NET makes it quite difficult, next to impossible. I followed this question
Running a Stored Procedure in C# Button but found out

does not return the output from query.

I tried this other approach but can't seem to pass the paremeters in this way

SqlConnection myConnection = new SqlConnection(myconnectionString);

SqlCommand myCommand = new SqlCommand();
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "usp_GetCustomer";

myCommand.SelectParameter <-- does not exist

Can someone write this simple code, how can I implement it? Basically I am passing a
(both character strings) to stored procedure and it returns a number that I want to capture and assign to a label control.

Thank you

The output from my query is this. It runs a complex query, create a temp table and then it runs

select @@rowcount

and I am capturing that.

Answer Source
  1. Don't use ExecuteNonQuery if you actually want data from a result set.

  2. Make sure your procedure uses set nocount on

  3. Then use SqlCommand.ExecuteScalar()

    return (int)myCommand.ExecuteScalar(); // value of select @@rowcount

Edit: As for your parameters:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download