Executing a stored proc and getting the return value

by timvasil 11/11/2007 3:27:00 PM

Here's a handy way to execute a stored proc and get both the return value and any datatables.

public int ExecStoredProcedure(string procName, out DataSet dataSet, params SqlParameter[] parameters)
{
    // Prepare the stored proc execution
    using (SqlCommand cmd = new SqlCommand(procName, _dbConnection, _transaction))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        // Add regular parameters (in, out, inout)
        if (parameters != null)
        {
            foreach (SqlParameter parameter in parameters)
            {
                cmd.Parameters.Add(parameter);
            }
        }

        // Add return value parameter
        SqlParameter retValParam = cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.Int);
        retValParam.Direction = ParameterDirection.ReturnValue;

        // Execute the proc
        dataSet = new DataSet();
        using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
        {
            dataAdapter.Fill(dataSet);
        }

        // Extract the return value
        return (int)retValParam.Value;
    }
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

ADO.NET

Related posts

Comments are closed

 

About the author

Tim Vasil Tim Vasil
I'm a software engineer living in Cambridge, MA.

E-mail me Send mail

Search

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Recent comments