I have this loop, which updates @UpdateBlockSize number of records on each iteration:
WHILE 1=1
BEGIN
UPDATE TOP (@UpdateBlockSize) table1
SET field1 = nv.value
FROM table1 i
INNER JOIN #table2 nv ON nv.id = i.id
IF @@ROWCOUNT < @UpdateBlockSize BREAK
END
Question:
How can I ensure that each iteration works within a transaction so that if it fails, only that iteration is rolled back and the LOOP exits?
Any single update that fails is it’s own transaction (assuming no explicit outer transaction).
If I understand you correctly…
So, try this
If you want a single transaction for all loops, then don’t use a loop. The transaction log will contain all rollback information for all loops because it is a single transaction. Unless this is abbreviated code, a loop adds no value in this case…