如何通过C#代码在Sql中执行批量更新

我想更新多行,如下所示

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

(这里根据一些复杂的逻辑评估s_id )。
出于性能原因,更新应该分批进行。 有没有办法批处理更新语句并通过单个执行语句执行批处理? 我知道在JAVA中我们可以通过JDBC实现这一点。 在C#中有类似的方式吗?

提前致谢

是的,您可以使用SqlDataAdapter 。

SqlDataAdapter具有InsertCommand和UpdateCommand属性,允许您指定用于将新行插入数据库的SQLCommand和用于分别更新数据库中的行的SqlCommand。

然后,您可以将DataTable传递给dataadapter的Update方法,它会将语句批处理到服务器 – 对于DataTable中作为新行的行,它会执行INSERT命令,对于已修改的行,它会执行UPDATE命令。

您可以使用UpdateBatchSize属性定义批处理大小。

这种方法允许您处理大量数据,并允许您以不同方式很好地处理错误,即如果特定更新遇到错误,您可以告诉它不要抛出exception但继续执行剩余的通过设置ContinueUpdateOnError属性进行更新。

是的,您可以构建一个纯文本SQL命令(为安全性参数化),如下所示:

 SqlCommand command = new SqlCommand(); // Set connection, etc. for(int i=0; i< items.length; i++) { command.CommandText += string.Format("update mytable set s_id=@s_id{0} where id = @id{0};", i); command.Parameters.Add("@s_id" + i, items[i].SId); command.Parameters.Add("@id" + i, items[i].Id); } command.ExecuteNonQuery(); 

使用StringBuilder(System.Text.StringBuilder)来构建您的Sql,例如:

 StringBuilder sql = new StringBuilder(); int batchSize = 10; int currentBatchCount = 0; SqlCommand cmd = null; // The SqlCommand object to use for executing the sql. for(int i = 0; i < numberOfUpdatesToMake; i++) { int sid = 0; // Set the s_id here int id = 0; // Set id here sql.AppendFormat("update mytable set s_id = {0} where id = {1}; ", sid, id); currentBatchCount++; if (currentBatchCount >= batchSize) { cmd.CommandText = sql.ToString(); cmd.ExecuteNonQuery(); sql = new StringBuilder(); currentBatchCount = 0; } } 

创建一组这些更新(填入id),在一个字符串中用分号分隔,将结果字符串设置为SqlCommand的CommandText属性,然后调用ExecuteNonQuery()。