Jeremy Stein - Brain

« »

.NET Generic Method to Run a Stored Procedure

Don’t you wish you could call your stored procedures just like they were methods in another class? Using .NET 1.1, I added a method like this to a utility class:

public static DataTable ExecuteQuery(
  string spName,
  params object[] args)
{
  using (SqlConnection conn =
         new SqlConnection(Global.ConnString))
  {
    using (SqlCommand command =
           new SqlCommand(spName, conn))
    {
      command.CommandType = CommandType.StoredProcedure;
      for (int i=0; i<args.Length-1; i+=2)
      {
        command.Parameters.Add(
          args[i].ToString(), args[i+1]);
      }
      using (SqlDataAdapter adapter =
             new SqlDataAdapter(command))
      {
        DataTable table = new DataTable();
        adapter.Fill(table);
        return table;
      }
    }
  }
}

March 29, 2006 No Comments.

No Comments

Be the first to comment!

Leave a Reply

Your email address will not be published. Required fields are marked *

Why ask?

« »