Q: I want to update a large table in batches in the form of 5,000 rows at a time, but I don't know how to split the data. This table does not contain incremental numbers or integer primary keys. How can we achieve data update while maintaining good performance? A: If you know which rows have not been updated, you can use a simple predicate to exclude the updated rows. the ROWCOUNT setting helps you split data in batches. q: I want to update a large table in batches with 5,000 rows at a time, but I don't know how to split the data. This table does not contain incremental numbers or integer primary keys. How can we achieve data update while maintaining good performance?
A: If you know which rows have not been updated, you can use simple predicates to exclude updated rows. the ROWCOUNT setting can help you split data in batches. The following code list shows how to use this setting:
Set rowcount 1000
WHILE (1 = 1) BEGIN
BEGIN TRANSACTION
UPDATE... set..., MyLastUpdate = 'Date',... WHERE
MyLastUpdate <'date'
-- Update row 1000 not updated
IF @ ROWCOUNT = 0
BEGIN
COMMIT TRANSACTION
BREAK
END
COMMIT TRANSACTION
END
When the specified number of rows is returned, ROWCOUNT causes SQL Server to stop query processing. This technology is useful because it avoids the concurrent hit caused by a large number of updates. the fewer the number of rows in the update, the less likely the update task will make other users unable to access the data. Combined with transaction log backup, this method can also minimize the size of your transaction logs.
If the update row is not identified, you can use a cursor to traverse all data and submit each x value. However, cursors usually consume more time than set-based statements.
-Microsoft SQL Server Development team