我写了如下代码:
for (int i = 0; i < ListToUpdate.Count; i = i + 500)
{
SqlCommand command = new SqlCommand();
command.Connection = new SqlConnection("Data Source=.;Initial Catalog=mydb;Integrated Security=SSPI");
command.Connection.Open();
var batchList = ListToUpdate.Skip(i).Take(500);
for (int j = 0; j < batchList.Count(); j++)
{
command.CommandText += string.Format("update mytable set column=@s_id{0} where columnid = @id{0};", j);
command.Parameters.AddWithValue("@s_id" + j, ListToUpdate[j].QuantitySoldTotal);
command.Parameters.AddWithValue("@id" + j, ListToUpdate[j].ItemId);
}
command.ExecuteNonQuery();
command.Connection.Close();
}
这应该批量更新我的表,但奇怪的是查询只在第一次执行...
如果列表中有 1500 个项目,只有第一批得到更新...而其他的则不会...
我在这里做错了什么???
最佳答案
是否每次迭代都要关闭并重新打开连接?一旦打开连接,只需在每次批量更新后使用
创建一个新的 sql 命令文本command.CommandText = CommandType.Text;
我建议这个 -
SqlCommand command = new SqlCommand();
command.Connection = new SqlConnection("Data Source=.;Initial Catalog=mydb;Integrated Security=SSPI");
command.Connection.Open();
for (int i = 0; i < ListToUpdate.Count; i = i + 500) {
var batchList = ListToUpdate.Skip(i).Take(500);
for (int j = 0; j < batchList.Count(); j++) {
command.CommandText += string.Format("update mytable set column=@s_id{0} where columnid = @id{0};", j);
command.Parameters.AddWithValue("@s_id" + j, batchList[j].QuantitySoldTotal);
command.Parameters.AddWithValue("@id" + j, batchList[j].ItemId)
}
command.ExecuteNonQuery();
command.CommandText = CommandType.Text;
}
command.Connection.Close();
从生成的新列表中选择属性,例如 batchList[j]
。
关于c# - SQLCommand批量更新查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43609557/