29

我有一个 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"}

4

1 回答 1

75

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

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

于 2013-10-18T11:48:40.573 回答