如何从SqlDataReader读取多个结果集?

时间:2013-10-18 11:46:10

标签: c# .net sqldatareader multiple-resultsets

我有一个SP,我试图返回2个结果集,在我的.cs文件中我正在尝试这样的事情:

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

但是我得到了:

  

错误:IndexOutOfRange {“EntityName”}

1 个答案:

答案 0 :(得分:58)

这里有一个关于如何使用数据读取器处理多个结果集的示例

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());
    }
}

从多个数据集中检索数据的关键是使用reader.NextResult