Saturday, April 18, 2015

Nest a do loop inside of an .ExecuteReader implementation to make something happen for every row returned from a sproc.

sqlConnection.Open();
using (var command = new SqlCommand("whatever", sqlConnection)
   {
      CommandType = CommandType.StoredProcedure
   })
{
   command.Parameters.Add(CreateParameter("foo", "bar"));
   using (var row = command.ExecuteReader())
   {
      if (row.Read())
      {
         do
         {
            string stuff = Convert.ToString(row["myColumn"]);
            DoThatThingYouDo(stuff);
         } while (row.Read());
      }
   }
}

 
 

...will run the DoThatThingYouDo method for every row returned while the following will only do so for the first row:

sqlConnection.Open();
using (var command = new SqlCommand("whatever", sqlConnection)
   {
      CommandType = CommandType.StoredProcedure
   })
{
   command.Parameters.Add(CreateParameter("foo", "bar"));
   using (var row = command.ExecuteReader())
   {
      if (row.Read())
      {
         string stuff = Convert.ToString(row["myColumn"]);
         DoThatThingYouDo(stuff);
      }
   }
}

No comments:

Post a Comment