【发布时间】:2017-10-25 06:43:02
【问题描述】:
我正在尝试找出通过 SQL Server 中的迷你控制台应用程序执行批量更新的最佳方法。我已经编写了自己的批量更新方式,如下所示:
SqlCommand command = new SqlCommand();
command.Connection = new SqlConnection("Data Source=.;Initial Catalog=mydb;Integrated Security=SSPI");
command.Connection.Open();
for (int i = 0; i < items.Count; i = i + 1000)
{
var batchList = items.Skip(i).Take(1000).ToList();
for (int j = 0; j < batchList.Count(); j++)
{
command.CommandText += string.Format("update Items set QuantitySold=@s_id{0} where ItemID = @id{0};", j);
command.Parameters.AddWithValue("@s_id" + j, batchList[j].QuantitySold);
command.Parameters.AddWithValue("@id" + j, batchList[j].ItemID);
}
command.ExecuteNonQuery();
command = new SqlCommand();
command.Connection = new SqlConnection("Data Source=.;Initial Catalog=mydb;Integrated Security=SSPI");
command.Connection.Open();
}
command.Connection.Close();
但是我对这个性能不太满意,更新我的数据库中的 50000-100000 条记录时,这样做会变得很慢,即使它以 1000 条为单位进行更新......
是否有任何可以“加快速度”的库/解决方案?
有人可以帮帮我吗?
【问题讨论】:
-
如果您创建基于集合的更新而不是为每一行单独更新,这会快很多。我会考虑创建一个表参数并将其移至存储过程。
-
在您的数据库中创建一个队列并将记录转储到其中,让数据库进程更新数据。插入物既便宜又快速。
-
@SeanLange 你能以回答的形式回复,以便我能明白你的意思吗? =)
-
设置更新是要走的路,但是速度慢的另一个原因是因为你一直在打开和关闭连接,而且没有必要这样做,在一个上进行。
-
而且,您不需要不断地创建不同数字的参数。设置您的命令对象一次,然后只需不断更改参数(不是名称)的值以保持传递更新。
标签: c# sql-server performance c#-4.0 bulkupdate