我如何返回多个结果集的SqlCommand? [英] How do I return multiple result sets with SqlCommand?

查看:1093
本文介绍了我如何返回多个结果集的SqlCommand?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以执行多个查询,并返回其结果执行的SqlCommand 只有一次?

Can I execute multiple queries and return their results executing a SqlCommand just once?

推荐答案

见的 SqlDataReader.NextResult (一个SqlDataReader的是从调用的 SqlCommand.ExecuteReader ):

See SqlDataReader.NextResult (an SqlDataReader is returned from calling SqlCommand.ExecuteReader):

,使数据读取到下一个结果[设置]读取批处理的Transact-SQL语句的结果时。

Advances the data reader to the next result [set], when reading the results of batch Transact-SQL statements.

例如:

string commandText = @"SELECT Id, ContactId
FROM dbo.Subscriptions;

SELECT Id, [Name]
FROM dbo.Contacts;";


List<Subscription> subscriptions = new List<Subscription>();
List<Contact> contacts = new List<Contact>();

using (SqlConnection dbConnection = new SqlConnection(@"Data Source=server;Database=database;Integrated Security=true;"))
using (SqlCommand dbCommand = new SqlCommand(commandText, dbConnection))
{
    dbCommand.CommandType = CommandType.Text;
    dbConnection.Open();

    SqlDataReader reader = dbCommand.ExecuteReader();

    while (reader.Read())
    {
        subscriptions.Add(
            new Subscription()
            {
                Id = (int)reader["Id"],
                ContactId = (int)reader["ContactId"]
            });
    }

    reader.NextResult();

    while (reader.Read())
    {
        contacts.Add(
            new Contact()
            {
                Id = (int)reader["Id"],
                Name = (string)reader["Name"]
            });
    }

    dbConnection.Close();
}

其他例子:

  • C#多个结果集
  • <一个href="http://www.java2s.com/Tutorial/CSharp/0560__ADO.Net/ExecutingaQueryThatReturnsMultipleResultSetswithSqlDataReader.htm"相对=nofollow>执行查询返回多个结果集SqlDataReader对象:SqlCommand的选择«ADO.Net«C#/ CSHARP教程
  • C# Multiple Result Sets
  • Executing a Query That Returns Multiple Result Sets with SqlDataReader : SqlCommand Select « ADO.Net « C# / CSharp Tutorial

这篇关于我如何返回多个结果集的SqlCommand?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆