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.

Related podcasts

Events coming up

  • Mar 15

    DevWeek 2010

    London, United Kingdom

    DevWeek is Europe’s leading independent conference for software developers, database professionals and IT architects, and features expert speakers on a wide range of topics, including .NET 4.0, Silverlight 3, WCF 4, Visual Studio 2010, REST, Windows Workflow 4, Thread Synchronization, ASP.NET 4.0, SQL Server 2008 R2, LINQ, Unit Testing, CLR & C# 4.0, .NET Patterns, WPF 4, F#, Windows Azure, ADO.NET, Entity Framework, Debugging, T-SQL Tips & Tricks, and more.

Want to stay in touch with what's going on? Follow us on twitter!