What I am trying to do is similar to what the OP asked here:
I am trying to store the results of one or more SQL queries into separate DataTables. The problem with the above question's approach is that it only works for discrete values in each result set. It would be preferable to use DataTables Load(reader
) method to store each result set in a single statement than having to iterate over all of DataReader's columns.
In the code below I have two SQL queries (although this should work for an arbitrary number of queries) whose results I attempt to store in a temporary data-table and then to a list of datatables. The problem with my code is that it only returns the first query's result set, and adding subsequent queries throws a Reader is closed exception
.
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand
("SELECT TOP 10 Column1, Column2 FROM Table1; SELECT TOP 10 Column1, Column2 FROM Table2", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
tempTable.Reset();
tempTable.Load(reader);
dataTables.Add(tempTable);
}
if (reader.NextResult())
{
while (reader.Read())
{
tempTable.Reset();
tempTable.Load(reader);
dataTables.Add(tempTable);
}
}
}
}
}
I have struggled for hours with this. I am not sure if the DataTable/DataReader is just poorly designed for my use case or if there is something basic I am missing here.