如何使用SqlCommand返回多个结果集?
我可以执行多个查询并返回SqlCommand一次执行的结果吗?
回答:
请参见SqlDataReader.NextResult(通过调用SqlCommand.ExecuteReader返回SqlDataReader ):
在读取批处理Transact-SQL语句的结果时,将数据读取器前进到下一个结果[set]。
例:
string commandText = @"SELECT Id, ContactIdFROM 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;"))
{
    dbConnection.Open();
    using (SqlCommand dbCommand = dbConnection.CreateCommand())
    {
        dbCommand.CommandText = commandText;
        using(SqlDataReader reader = dbCommand.ExecuteReader())
        {
            while(reader.Read())
            {
                subscriptions.Add(new Subscription()
                {
                    Id = (int)reader["Id"],
                    ContactId = (int)reader["ContactId"]
                });
            }
            // this advances to the next resultset 
            reader.NextResult();
            while(reader.Read())
            {
                contacts.Add(new Contact()
                {
                    Id = (int)reader["Id"],
                    Name = (string)reader["Name"]
                });
            }
        }
    }
}
其他例子:
- C#多个结果集
 - 使用SqlDataReader执行返回多个结果集的查询:SqlCommand选择«ADO.Net«C#/ CSharp教程
 
以上是 如何使用SqlCommand返回多个结果集? 的全部内容, 来源链接: utcz.com/qa/412344.html
