Search code examples
c#dbdatareader

How best to loop over a batch of Results with a C# DbDataReader


I'm executing a number of SQL query's as a batch and then getting all of the result sets back in a batch. The way that my code is currently put together, the first result set gets skipped. Now that I know this, I could simply throw in another statement outside of my loop that grabs the first result, however I'm wondering if there is a more elegant solution to this problem.

Here is some sudo code of whats going on:

DbDataReader reader= /*some stuff that returns a batch of results...*/;

while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do things with the data....
       }
   }
}

Now i would have expected that NextResult() advances you to the first result the first time you call it, which is what Read() seems to do. However what it actually seems to do is bring you to the second result on the first call. Am I misunderstanding how you're expected to use this method, or are you really expected to do some like the following:

DbDataReader reader= /*some stuff that returns a batch of results...*/;

//this deals with the row in the the very first result
while (reader.Read())
{
    if (!reader.IsDBNull(0))
    {
        //do things with the data....
    }
}

//this deals with the rest of the rows...
while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do exact same things with the data....
           //is this not pretty klugey?
       }
   }
}

This strikes me as rotten programming style, but I don't see a way around it. Does anyone know of a more elegant solution to this?


Solution

  • Simply put the NextResult at the end of the loop instead of the beginning:

    do {
       while (reader.Read()) {
          if (!reader.IsDBNull(0)) {
             //do things with the data....
          }
       }
    } while (reader.NextResult());