Recipe 2.4 · C#
Replacing Cursors with Set-Based SQL
Problem
A nightly job applies late fees to overdue invoices. It loops through them with a cursor, one row at a time. It ran in two minutes when the company had 5,000 open invoices. Now it has 400,000 and the job runs into business hours.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
-- Not to copy: row-by-row processing.
DECLARE @Id int, @Balance money
DECLARE c CURSOR FOR
SELECT InvoiceId, Balance FROM Invoice
WHERE DueDate < @AsOf AND Balance > 0
AND LateFeeAppliedOn IS NULL
OPEN c
FETCH NEXT FROM c INTO @Id, @Balance
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE Invoice
SET LateFee = ROUND(@Balance * 0.015, 2),
LateFeeAppliedOn = @AsOf
WHERE InvoiceId = @Id
INSERT INTO InvoiceNote (InvoiceId, NoteDate, Note)
VALUES (@Id, @AsOf, 'Late fee applied')
FETCH NEXT FROM c INTO @Id, @Balance
END
CLOSE c
DEALLOCATE c
Each loop iteration is two statements, each with its own plan execution, locks and log records. The cursor is global and dynamic by default, the slowest kind. And there is no transaction: if the job dies halfway, half the invoices have fees and nothing says which.
The improved recipe
CREATE OR ALTER PROCEDURE dbo.Invoice_ApplyLateFees
@AsOfDate DATE,
@FeeRate DECIMAL(9, 6) = 0.015
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
DECLARE @Applied TABLE
(
InvoiceId INT NOT NULL PRIMARY KEY,
Fee DECIMAL(19, 4) NOT NULL
);
BEGIN TRANSACTION;
UPDATE i
SET i.LateFee = ROUND(i.Balance * @FeeRate, 2),
i.LateFeeAppliedOn = @AsOfDate
OUTPUT inserted.InvoiceId, inserted.LateFee
INTO @Applied (InvoiceId, Fee)
FROM dbo.Invoice AS i
WHERE i.DueDate < @AsOfDate
AND i.Balance > 0
AND i.LateFeeAppliedOn IS NULL;
INSERT INTO dbo.InvoiceNote (InvoiceId, NoteDate, Note)
SELECT a.InvoiceId,
@AsOfDate,
CONCAT(N'Late fee applied: ', a.Fee)
FROM @Applied AS a;
COMMIT TRANSACTION;
SELECT COUNT(*) AS InvoicesCharged,
COALESCE(SUM(a.Fee), 0) AS TotalFees
FROM @Applied AS a;
END;
How it works
The cursor's loop body becomes one UPDATE with a WHERE clause that describes every row the loop used to visit. The OUTPUT ... INTO clause captures exactly which invoices were changed and by how much, so the follow-up INSERT writes one note per changed invoice in a single statement. Both statements run in one transaction, so the job either applies all the fees or none.
The final SELECT returns a summary the calling job can log. Because the update only touches invoices where LateFeeAppliedOn IS NULL, running the job twice does not charge twice.
The way to convert any cursor is the same: write down what the loop does to each row, then ask which rows it does it to. The second answer becomes a WHERE clause or a join, and the first becomes the SET list or the SELECT list.
Variations and pitfalls
- Running totals are the other classic cursor job. Window functions (SQL Server 2012 and later) do it in one pass:
SELECT t.AccountId,
t.PostedOn,
t.Amount,
SUM(t.Amount) OVER (
PARTITION BY t.AccountId
ORDER BY t.PostedOn, t.TransactionId
ROWS UNBOUNDED PRECEDING) AS RunningBalance
FROM dbo.AccountTransaction AS t;
- Huge updates. If one statement would touch millions of rows and hold locks too long, loop in batches with
UPDATE TOP (5000)until@@ROWCOUNTis zero. That is batching, not row-by-row processing, and it is fine. - When a cursor is acceptable. Calling a stored procedure per row that you cannot rewrite, sending one e-mail per row from an admin script, or running maintenance across databases. Declare it
LOCAL FAST_FORWARDso it is cheap and does not leak out of the procedure. WHILEloops over a table variable are a cursor with extra steps. The same rewrite applies.- Scalar functions in the
SETlist can turn a set-based statement back into row-by-row execution. SQL Server 2019 inlines many scalar functions, but check the plan.