有没有一种简单的方法可以并行执行查询?我有一个类似这样的查询:
delete from TableA where id = @id
delete from TableB where id = @id
delete from TableC where id = @id
...
我想同时进行。我也可以使用 C#,但不确定如何使用。
最佳答案
第一个想法是拥有单独的线程和单独的连接,但我认为您可以使用异步回调在单个线程中管理多个连接:
string[] tables = new string[] { "TableA", "TableB", "TableC" ... };
var runningCommands = new List<SqlCommand>();
foreach(var table in tables)
{
var conn = new SqlConnection(...);
conn.Open();
var cmd = new SqlCommand("DELETE FROM " + table + " WHERE id = @id");
cmd.Parameters.Add(new SqlParameter("@id", id);
cmd.BeginExecuteNonQuery();
runningCommands.Add(cmd);
}
// now wait for all of them to finish executing
foreach(var cmd in runningCommands)
{
cmd.EndExecuteNonQuery();
cmd.Connection.Close();
}
关于c# - SQL Server 2008——并行执行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8074039/