【发布时间】:2010-02-24 15:23:19
【问题描述】:
我想像下面这样更新多行
update mytable set s_id = {0} where id = {1}
(这里s_id是根据一些复杂的逻辑进行评估的)。
出于性能原因,更新应该分批进行。有没有办法批量更新语句并通过单个执行语句执行批处理?我知道在 JAVA 中我们可以通过 JDBC 做到这一点。 C#中是否有类似的方法?
提前致谢
【问题讨论】:
我想像下面这样更新多行
update mytable set s_id = {0} where id = {1}
(这里s_id是根据一些复杂的逻辑进行评估的)。
出于性能原因,更新应该分批进行。有没有办法批量更新语句并通过单个执行语句执行批处理?我知道在 JAVA 中我们可以通过 JDBC 做到这一点。 C#中是否有类似的方法?
提前致谢
【问题讨论】:
使用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;
}
}
【讨论】:
int id = 0 的人都可以轻松更改整个查询。
是的,您可以构建一个纯文本 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();
【讨论】:
是的,您可以使用SqlDataAdapter。
SqlDataAdapter 具有InsertCommand 和UpdateCommand 属性,允许您指定用于将新行插入数据库的SQLCommand 和用于分别更新数据库中的行的SqlCommand。
然后您可以将 DataTable 传递给 dataadapter 的 Update 方法,它会将语句批量发送到服务器 - 对于 DataTable 中的行是新行,它执行 INSERT 命令,对于修改过的行它执行 UPDATE 命令。
您可以使用UpdateBatchSize 属性定义批量大小。
这种方法允许您处理大量数据,并允许您以不同的方式很好地处理错误,即如果在特定更新中遇到错误,您可以告诉它不要抛出异常而是继续通过设置ContinueUpdateOnError 属性来进行剩余更新。
【讨论】:
创建一组这些更新(填充 id),用分号将它们分隔在一个字符串中,将结果字符串设置为 SqlCommand 的 CommandText 属性,然后调用 ExecuteNonQuery()。
【讨论】: