如何在SQL通过C#代码执行批量更新 [英] How to perform batch update in Sql through C# code

查看:1063
本文介绍了如何在SQL通过C#代码执行批量更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要更新一样多行下方

update mytable set s_id = {0} where id = {1}

(这里的 S_ID 评估基于一些复杂逻辑)。结果
对于性能原因,更新应该分批发生。有什么办法来批量更新语句,并通过单一的执行语句执行批处理?我知道,在JAVA中,我们可以通过JDBC做到这一点。有没有在C#中类似的方式?

(Here s_id is evaluated based on some complex logic).
For performance reason, updates should happen in batches. Is there any way to batch the update statements and execute the batch through single execute statements? I know in JAVA we can do this through JDBC. Is there similar way in C#?

在此先感谢

推荐答案

是的,你可以使用 SqlDataAdapter的

的SqlDataAdapter有的InsertCommand 并的更新命令属性,让你可以指定的SqlCommand用来插入新行插入到数据库和的SqlCommand更新的行数据库分别。

The SqlDataAdapter has InsertCommand and UpdateCommand properties which allow you to specify an SQLCommand to use to insert new rows into the database and an SqlCommand to update rows in the database respectively.

您可以然后通过一个DataTable到的更新 DataAdapter的方法,它会批出语句到服务器 - 在数据表是新行的行,执行INSERT命令,修改了行它执行UPDATE命令。

You can then pass a DataTable to the Update method of the dataadapter, and it will batch up the statements to the server - for rows in the DataTable that are new rows, it executes the INSERT command, for modified rows it executes the UPDATE command.

您可以使用的 UpdateBatchSize 属性。

这方法可以让你处理大量数据,并允许您很好地以不同的方式处理错误,也就是说,如果一个特定的更新中遇到错误时,你可以告诉它不要抛出一个异常,而是通过设置的 ContinueUpdateOnError的属性。

This approach allows you to deal with large volumes of data, and allows you to nicely handle errors in different ways, i.e. if an error is encountered with a particular update, you can tell it to NOT throw an exception but to carry on with the remaining updates by setting the ContinueUpdateOnError property.

这篇关于如何在SQL通过C#代码执行批量更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆