我有一种情况,我有一堆都需要执行的 SQL 更新命令。我知道 DataSets 可以进行批量更新,但我能够完成它的唯一方法是首先将整个表加载到数据集中。如果我只想更新表中记录的子集怎么办?
2 回答
这里最简单的方法是加载具有所需行(您要更新的行)的表。仔细检查 RowState 是否为“已插入”。使用执行“更新”的存储过程(包装在 SqlCommand 中)分配适配器的 InsertCommand 属性,此调整将确保表中存在的所有行都得到更新。
这里的基础是:DataAdapter 对状态为已更新的行运行 UpdateCommand,为状态为已插入的行运行 InsertCommand,最后为状态为已删除的行运行 DeleteCommand。
EDITED: Based on your comment, I'd recommend using the Bulk Copy method to go to a staging table first. Then you can do a single update on your real table based on the staging table.
=========
One way is to build the SQL Command yourself; however, I'd recommend reading about the SQL Injection possibilities to protect yourself. Depending on your situation and your platform there are other options.
For example if you are dealing with a lot of data, then you could do a bulk import into a holding table, which you would then issue a single update command off of. I've also had good success passing records in as XML (I found in my environment that I needed at least 50 rows to offset the cost of loading the DOM, and I knew that the scalability issues were not a factor in my case).
Some other things I've seen was people package the updates into a binary field, for example one binary field for each column, then they have a function which unpacks the binary field. Again you will want to test with your environment.
With that said, have you verified that simply calling a single update command or stored procedure for each update you need is not sufficent? You might not even need to batch the commands up.
- Josh
Watch out for Premature Optimization it can be killer!