How to run through multiple DataReader results

You can save code by piling SQL statements into one SqlCommand and then getting a DataReader with multiple result sets. This code shows you how to run through these.

/*
using System.Data;
using System.Data.SqlClient;
*/

SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["con"]);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT TOP 3 * FROM Employees ORDER BY LastName;SELECT TOP 3 * FROM Employees ORDER BY LastName DESC",con);
SqlDataReader dr = cmd.ExecuteReader();
do {
  while(dr.Read()) {
    System.Diagnostics.Debug.WriteLine(dr["LastName"]);
  }
} while(dr.NextResult());
con.Close();

You might also like...

Comments

Edward Tanguay Edward Tanguay updates his personal web site tanguay.info weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“In theory, theory and practice are the same. In practice, they're not.”