Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read multiple resultset from SqlDataReader? [duplicate]

I have a SP from that I am trying to return 2 result set from, and in my .cs file i am trying something like this:

dr = cmd.ExecuteReader();
while (dr.Read())
{
  RegistrationDetails regDetails = new RegistrationDetails()
  {
    FName = dr["FName"].ToString(),
    LName = dr["LName"].ToString(),
    MName = dr["MName"].ToString(),
    EntityName = dr["EntityName"].ToString(),// in 2nd result set
    Percentage = dr["Percentage"].ToString()// in 2nd result set
   };
}

However I am getting an :

error:IndexOutOfRange {"EntityName"}

like image 272
Rocky Avatar asked Oct 18 '13 11:10

Rocky


People also ask

How do I return multiple result sets with SqlCommand?

Advances the data reader to the next result [set], when reading the results of batch Transact-SQL statements. Other examples: C# Multiple Result Sets. Executing a Query That Returns Multiple Result Sets with SqlDataReader : SqlCommand Select « ADO.Net « C# / CSharp Tutorial.

What can be used to return multiple result sets?

In order to get multiple result sets working we need to drop to the ObjectContext API by using the IObjectContextAdapter interface. Once we have an ObjectContext then we can use the Translate method to translate the results of our stored procedure into entities that can be tracked and used in EF as normal.

Can DataReader have multiple tables?

Answers. It IS possible to handle multiple result sets with a reader. string sqlText = "Select this, that from here; select somethingelse from there"; ...

Can a stored procedure return multiple result sets?

Most stored procedures return multiple result sets. Such a stored procedure usually includes one or more select statements. The consumer needs to consider this inclusion to handle all the result sets.


1 Answers

Here you have a sample about how to handle multiple result sets with a data reader

static void RetrieveMultipleResults(SqlConnection connection) {     using (connection)     {         SqlCommand command = new SqlCommand(           "SELECT CategoryID, CategoryName FROM dbo.Categories;" +           "SELECT EmployeeID, LastName FROM dbo.Employees",           connection);         connection.Open();          SqlDataReader reader = command.ExecuteReader();          do         {             Console.WriteLine("\t{0}\t{1}", reader.GetName(0),                 reader.GetName(1));              while (reader.Read())             {                 Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0),                     reader.GetString(1));             }                        }         while (reader.NextResult());     } } 

The key for retrieving data from multiple data sets is using reader.NextResult

like image 129
Claudio Redi Avatar answered Oct 07 '22 21:10

Claudio Redi