SQL Server 2008 — execute queries in parallel

2020-07-31 03:34发布

Is there an easy way to execute queries in parallel? I have a query that has something like this:

delete from TableA where id = @id
delete from TableB where id = @id
delete from TableC where id = @id
...

and I want to do them in parallel. I can also use C#, though not sure how.

3条回答
beautiful°
2楼-- · 2020-07-31 04:08

First idea is to have separate threads and separate connections but I think you can manage it with multiple connections in a single thread using async callbacks:

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();
}
查看更多
叛逆
3楼-- · 2020-07-31 04:10
    List<string> list;
    list.Add("query1");
    list.Add("query2");
    list.AsParallel().ForAll(query => ExecuteQuery(query));
查看更多
趁早两清
4楼-- · 2020-07-31 04:31

Use SSIS. Put 3 Execute sql tasks on the control flow. Add a delete statement to each task. When the package executes, they will all get executed at the same time.

You could also create a job for each statement and schedule them all to run at the same time.

Async callback would also work, but the 2 above are easier for someone with a dba skillset to implement and manage.

查看更多
登录 后发表回答