So, I came across some code that is supposed to help me to update a massive table (100m+ records) by doing it in batches, as follows:
--Declare variable for row count
set rowcount 50000
go
Declare @rc int
Set @rc=50000
While @rc=50000
Begin
Begin Transaction
--Use tablockx and holdlock to obtain and hold
--an immediate exclusive table lock. This unusually
--speeds the update because only one lock is needed.
update MyTable With (tablockx, holdlock)
set TestField='ABC'
----Get number of rows updated
----Process will continue until less than 50000
select @rc=@@rowcount
Commit
End
Problem is, this goes into an infinite loop, priting (50000 row(s) affected) until the end of days. Incidentally, if the table has less than 50000 records the code above exits correctly. Anyone know how to fix this?
Thanks
if there are 50000 or more records in MyTable, then it will always update. You have no where clause in your update that would narrow the field to eventually getting you to <50000 records updated.
Presumably you intended to only update records where TestField <> ‘ABC’ so you didn’t perform the same update again.
When you’re thinking about what where clause to use, consider making use of the clustered index so you can perform an index seek/partial scan on your updates instead of a full table scan.
Incidentally,There is no need for the
HOLDLOCKhint since it is released as soon as the transaction commits, nor the explicit transaction since the update itself is a transaction. The tablock may yield a slight improvement since it avoids lock escalation.