How to read multiple resultset from SqlDataReader? [duplicate]
Asked Answered
R

1

33

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"}

Rhombencephalon answered 18/10, 2013 at 11:46 Comment(0)
A
92

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

Alexio answered 18/10, 2013 at 11:48 Comment(2)
Just came across this, would be better to use do { } while(reader.NextResult()) here. Result set could be empty and reader.HasRows will return false.Orgiastic
It's not only better, it's only correct way. Please fix accordingly as Neil M said. Simply put the HasRows exits too early e.g. if first result set is empty, and second one has results.Opaque

© 2022 - 2024 — McMap. All rights reserved.