DataReader

20 pts.
Tags:
.NET Framework 2.0
C#
DataReader
Can anybody explain with some code snippet how to run multiple queries with a single datareader in C# .Net 2.0
ASKED: May 30, 2008  7:17 AM
UPDATED: July 12, 2008  2:49 AM

Answer Wiki

Thanks. We'll let you know when a new response is added.

Hi,

The key here is to call NextResult on the SqlDataReader, rdr in the example below:

<pre> private static void GetDataReaderMultipleResults()
{
string connStr = “Data Source=.\\sqlexpress;AttachDbFilename=”C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\AdventureWorksLT_Data.mdf”;Initial Catalog=AdventureWorksLT_Data;Integrated Security=True”;

string selectStatements =
“select CustomerID, FirstName, LastName from SalesLT.Customer;select AddressID, AddressLine1, City, StateProvince from SalesLT.Address;”;

using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(selectStatements, conn))
{
conn.Open();

Console.WriteLine(“\nCustomers:\n”);

using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Console.WriteLine(
“ID: {0}, Name: {1} {2}”,
rdr[“CustomerID”>,
rdr[“FirstName”>,
rdr[“LastName”>);
}

Console.WriteLine(“\nAddresses:\n”);

rdr.NextResult();

while (rdr.Read())
{
Console.WriteLine(
“ID: {0}, Address: {1}, {2}, {3}”,
rdr[“AddressID”>,
rdr[“AddressLine1″>,
rdr[“City”>,
rdr[“StateProvince”>);
}
}
}
}</pre>

Joe

Discuss This Question:  

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.

Following