有没有一种简单的方法可以并行执行查询?我有这样的查询:
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(); }