How to read multiple resultset from SqlDataReader? [duplicate]

本秂侑毒 提交于 2019-12-17 18:48:15

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/19448899/how-to-read-multiple-resultset-from-sqldatareader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!