SQL script to update records in table row-by-row by using cursor

The MS SQL script below can be used to update records in a table row-by-row by using a cursor.

/**
 * The script below demonstrates how to perform row-by-row updates in SQL instead of bulk updates. 
 * This is particularly useful in scenarios where certain triggers only fire for single row updates 
 * and do not process bulk updates. By updating records one by one, you can ensure triggers behave 
 * as intended, allowing for correct API synchronization or similar workflows.
 */

DECLARE @CurrentRecordId AS uniqueidentifier;
DECLARE @UpdatedRowCount INT;

SET @UpdatedRowCount = 0;

-- Define a SELECT query to retrieve the IDs of the records to be updated
DECLARE record_cursor CURSOR FOR
  SELECT [RecordID]
  FROM   exampletables.ExampleTable

OPEN record_cursor;

FETCH NEXT FROM record_cursor INTO @CurrentRecordId;

WHILE @@FETCH_STATUS = 0
  BEGIN
      UPDATE exampletables.ExampleTable
      SET    [ChangedDate] = GETDATE()
      WHERE  [RecordID] = @CurrentRecordId;

	  SET @UpdatedRowCount = @UpdatedRowCount + 1;
      FETCH NEXT FROM record_cursor INTO @CurrentRecordId;
  END;

CLOSE record_cursor;

DEALLOCATE record_cursor;

PRINT 'Total number of records updated:';
PRINT @UpdatedRowCount;

By Leendert de Borst

Freelance software architect with 10+ years of experience. Expert in translating complex technical problems into creative & simple solutions.

Leave a comment

Your email address will not be published. Required fields are marked *