Home > Net >  Calling SQL Server stored procedure with result set and return value
Calling SQL Server stored procedure with result set and return value

Time:12-28

Is there a way to get a dataset and a return value from a SQL Server stored procedure with just one execution of the stored procedure?

Is there a way to get both in just one call?

TIA Marcos Galvani

SqlConnection conn = new SqlConnection(ConnectionString);

// Pick the stored procedure to be executed
SqlCommand cmd = new SqlCommand("CustomersList02", conn);
cmd.CommandType = CommandType.StoredProcedure;

// Set the parameters and return value
cmd.Parameters.Add(new SqlParameter("@Email", email));
cmd.Parameters.Add(new SqlParameter("@ReturnVal", SqlDbType.Int)).Direction = ParameterDirection.ReturnValue;

// Open the connection
conn.Open();

If I do this:

var dt = new DataTable();
dt.Load(cmd.ExecuteReader());

I don't get the return value, but if I do this:

cmd.ExecuteNonQuery();

I don't get the result set.

CodePudding user response:

You can do this in a single call.

using (SqlDataReader reader = cmd.ExecuteReader())
{
    var dt = new DataTable();
    dt.Load(reader);
}

// getthe return value.
int returnValue = (int)cmd.Parameters["@ReturnVal"].Value;
  • Related