Library code snippets

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();

Comments

  1. 02 Mar 2005 at 18:45

    An obscure side issue -


    I was using this technique with SQL Server with no problems but my app had to access Oracle as well. That gave me two problems; the OracleClient would not accept a ';' in the command string. This also meant that I did not find out how to make it accept multiple requests in one SQL statement.


    It might save some-one a day's struggle knowing that ('')

  2. 01 Jan 1999 at 00:00

    This thread is for discussions of How to run through multiple DataReader results.

Leave a comment

Sign in or Join us (it's free).

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.
AddThis

Related podcasts

Events coming up

  • Nov 18

    15 Minutes of Fame

    Dresher, United States

    This is a yearly tradition. We select 10 of the favorite speakers from monthly meetings, code camps, and hands on labs. Each one does a 15 minute talk on their favorite .NET technology. This is our 10th anniversary so we plan a gala event with special prizes and refreshments.

We'd love to hear what you think! Submit ideas or give us feedback