gpt4 book ai didi

c# - 如何使用 SqlCommand 返回多个结果集?

转载 作者:IT王子 更新时间:2023-10-29 03:55:12 24 4
gpt4 key购买 nike

我可以执行多个查询并仅执行一次 SqlCommand 返回它们的结果吗?

最佳答案

参见 SqlDataReader.NextResult (调用 SqlCommand.ExecuteReader 返回一个 SqlDataReader):

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;"))
{
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# - 如何使用 SqlCommand 返回多个结果集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12715620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com