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"]);
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()) {
} while(dr.NextResult());

You might also like...


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


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.

“Some people, when confronted with a problem, think "I know, I’ll use regular expressions." Now they have two problems.” - Jamie Zawinski