Skip to content

Cursors in SQL Server

SQL works on sets: one UPDATE statement changes thousands of rows at once. Sometimes, though, you need to process rows one at a time: call a stored procedure for each row, send each customer an email, or apply logic that depends on the previous row. A cursor lets you do that: it walks through the result of a SELECT row by row, like a foreach loop in C#.

Think of a cursor as a finger moving down a printed list: it points at one row, you work with that row, then it moves to the next. It works, but it's slow compared with handing the whole list over at once. That's why cursors should be the exception, not the rule.

Every output on this page comes from a real run on SQL Server 2025.

The cursor lifecycle

DECLARE  ->  OPEN  ->  FETCH (first row)  ->  WHILE @@FETCH_STATUS = 0
                                                 |  process the row
                                                 |  FETCH next row
                                              CLOSE  ->  DEALLOCATE
StepWhat it does
DECLARE ... CURSOR FOR SELECT ...Defines the cursor and the query it will walk through
OPENRuns the query and positions the cursor before the first row
FETCH NEXT ... INTO @variablesMoves to the next row and copies its columns into variables
@@FETCH_STATUS0 = a row was fetched; -1 = no more rows; -2 = the row was deleted
CLOSEReleases the result set and its locks; the cursor can be reopened
DEALLOCATERemoves the cursor definition completely

Setup: database and sample data

-- Create database if it does not exist
IF DB_ID('CursorPracticeDB') IS NULL
BEGIN
    CREATE DATABASE CursorPracticeDB;
END
GO

USE CursorPracticeDB;
GO

-- Drop table if it already exists
IF OBJECT_ID('dbo.CursorEmployeeDemo', 'U') IS NOT NULL
BEGIN
    DROP TABLE dbo.CursorEmployeeDemo;
END
GO

-- Create employee table
CREATE TABLE dbo.CursorEmployeeDemo
(
    EmployeeId INT IDENTITY(1,1) PRIMARY KEY,
    EmployeeName VARCHAR(100),
    Department VARCHAR(50),
    Salary DECIMAL(18,2),
    City VARCHAR(50)
);
GO

INSERT INTO dbo.CursorEmployeeDemo (EmployeeName, Department, Salary, City)
VALUES
('Rahul Sharma', 'IT', 80000, 'Indore'),
('Amit Verma', 'HR', 50000, 'Bhopal'),
('Priya Singh', 'IT', 90000, 'Pune'),
('Neha Jain', 'Finance', 65000, 'Indore'),
('Vikas Patel', 'IT', 75000, 'Mumbai'),
('Ankit Gupta', 'HR', 55000, 'Indore'),
('Sneha Mishra', 'Finance', 70000, 'Bhopal'),
('Rohit Sharma', 'IT', 95000, 'Pune'),
('Pooja Verma', 'HR', 60000, 'Mumbai'),
('Karan Mehta', 'Finance', 85000, 'Indore');
GO

-- Verify inserted records
SELECT * FROM dbo.CursorEmployeeDemo;
GO
Output
EmployeeIdEmployeeNameDepartmentSalaryCity
1Rahul SharmaIT80000.00Indore
2Amit VermaHR50000.00Bhopal
3Priya SinghIT90000.00Pune
4Neha JainFinance65000.00Indore
5Vikas PatelIT75000.00Mumbai
6Ankit GuptaHR55000.00Indore
7Sneha MishraFinance70000.00Bhopal
8Rohit SharmaIT95000.00Pune
9Pooja VermaHR60000.00Mumbai
10Karan MehtaFinance85000.00Indore

Example 1: Display all employees

USE CursorPracticeDB;
GO

DECLARE
    @EmployeeId INT,
    @EmployeeName VARCHAR(100),
    @Department VARCHAR(50),
    @Salary DECIMAL(18,2);

-- Step 1: Declare cursor
DECLARE EmployeeCursor CURSOR LOCAL FAST_FORWARD
FOR
SELECT
    EmployeeId,
    EmployeeName,
    Department,
    Salary
FROM dbo.CursorEmployeeDemo;

-- Step 2: Open cursor
OPEN EmployeeCursor;

-- Step 3: Fetch first record
FETCH NEXT FROM EmployeeCursor
INTO @EmployeeId, @EmployeeName, @Department, @Salary;

-- Step 4: Process records one by one
WHILE @@FETCH_STATUS = 0
BEGIN

    PRINT 'Employee ID: ' + CAST(@EmployeeId AS VARCHAR(10));

    PRINT 'Employee Name: ' + @EmployeeName;

    PRINT 'Department: ' + @Department;

    PRINT 'Salary: ' + CAST(@Salary AS VARCHAR(20));

    PRINT '--------------------------------';

    -- Fetch next employee
    FETCH NEXT FROM EmployeeCursor
    INTO @EmployeeId, @EmployeeName, @Department, @Salary;

END;

-- Step 5: Close cursor
CLOSE EmployeeCursor;

-- Step 6: Deallocate cursor
DEALLOCATE EmployeeCursor;
GO
Messages (first 3 of 10 employees)
Employee ID: 1
Employee Name: Rahul Sharma
Department: IT
Salary: 80000.00
--------------------------------
Employee ID: 2
Employee Name: Amit Verma
Department: HR
Salary: 50000.00
--------------------------------
Employee ID: 3
Employee Name: Priya Singh
Department: IT
Salary: 90000.00
--------------------------------
...

How it works:

  • The variables must match the cursor's SELECT columns in number, order and type, because FETCH ... INTO copies them by position.
  • The first FETCH comes before the loop. The loop checks @@FETCH_STATUS and fetches the next row at the end of each pass. Forgetting the FETCH inside the loop creates an endless loop on the first row.
  • PRINT output appears in the Messages tab, not in Results.
  • LOCAL FAST_FORWARD is the best default: LOCAL limits the cursor to this batch, and FAST_FORWARD makes it forward-only and read-only, the fastest kind of cursor.

Example 2: Process only IT employees

The cursor's SELECT is a normal query, so filter it with WHERE instead of skipping rows inside the loop:

DECLARE
    @EmployeeId INT,
    @EmployeeName VARCHAR(100),
    @Salary DECIMAL(18,2);

DECLARE ITEmployeeCursor CURSOR LOCAL FAST_FORWARD
FOR
SELECT EmployeeId, EmployeeName, Salary
FROM dbo.CursorEmployeeDemo
WHERE Department = 'IT';

OPEN ITEmployeeCursor;

FETCH NEXT FROM ITEmployeeCursor
INTO @EmployeeId, @EmployeeName, @Salary;

WHILE @@FETCH_STATUS = 0
BEGIN

    PRINT 'Employee ID: ' + CAST(@EmployeeId AS VARCHAR(10));

    PRINT 'Employee Name: ' + @EmployeeName;

    PRINT 'Salary: ' + CAST(@Salary AS VARCHAR(20));

    PRINT '-------------------------';

    FETCH NEXT FROM ITEmployeeCursor
    INTO @EmployeeId, @EmployeeName, @Salary;

END;

CLOSE ITEmployeeCursor;
DEALLOCATE ITEmployeeCursor;
GO
Messages
Employee ID: 1
Employee Name: Rahul Sharma
Salary: 80000.00
-------------------------
Employee ID: 3
Employee Name: Priya Singh
Salary: 90000.00
-------------------------
Employee ID: 5
Employee Name: Vikas Patel
Salary: 75000.00
-------------------------
Employee ID: 8
Employee Name: Rohit Sharma
Salary: 95000.00
-------------------------

Example 3: Increase salary employee by employee

DECLARE
    @EmployeeId INT,
    @EmployeeName VARCHAR(100),
    @OldSalary DECIMAL(18,2),
    @NewSalary DECIMAL(18,2);

DECLARE SalaryCursor CURSOR LOCAL FAST_FORWARD
FOR
SELECT EmployeeId, EmployeeName, Salary
FROM dbo.CursorEmployeeDemo
WHERE Department = 'IT';

OPEN SalaryCursor;

FETCH NEXT FROM SalaryCursor
INTO @EmployeeId, @EmployeeName, @OldSalary;

WHILE @@FETCH_STATUS = 0
BEGIN

    SET @NewSalary = @OldSalary * 1.10;

    UPDATE dbo.CursorEmployeeDemo
    SET Salary = @NewSalary
    WHERE EmployeeId = @EmployeeId;

    PRINT 'Employee: ' + @EmployeeName;

    PRINT 'Old Salary: ' + CAST(@OldSalary AS VARCHAR(20));

    PRINT 'New Salary: ' + CAST(@NewSalary AS VARCHAR(20));

    PRINT '-------------------------';

    FETCH NEXT FROM SalaryCursor
    INTO @EmployeeId, @EmployeeName, @OldSalary;

END;

CLOSE SalaryCursor;
DEALLOCATE SalaryCursor;
GO

-- Verify updated salaries
SELECT *
FROM dbo.CursorEmployeeDemo
WHERE Department = 'IT';
GO
Messages
Employee: Rahul Sharma
Old Salary: 80000.00
New Salary: 88000.00
-------------------------
Employee: Priya Singh
Old Salary: 90000.00
New Salary: 99000.00
-------------------------
Employee: Vikas Patel
Old Salary: 75000.00
New Salary: 82500.00
-------------------------
Employee: Rohit Sharma
Old Salary: 95000.00
New Salary: 104500.00
-------------------------
Output
EmployeeIdEmployeeNameDepartmentSalaryCity
1Rahul SharmaIT88000.00Indore
3Priya SinghIT99000.00Pune
5Vikas PatelIT82500.00Mumbai
8Rohit SharmaIT104500.00Pune

Each IT salary rose by 10%. The cursor here only reads (FAST_FORWARD); the change is made by a normal UPDATE ... WHERE EmployeeId = @EmployeeId, which is the simplest pattern.

The same update without a cursor

Example 3 needs four UPDATE statements, one per row. The set-based version needs one:

UPDATE dbo.CursorEmployeeDemo
SET Salary = Salary * 1.10
WHERE Department = 'IT';
Messages
(4 rows affected)

How much faster? A real measurement

We ran both approaches on a 100,000-row table, updating the 33,333 IT employees (cursor with LOCAL FAST_FORWARD, one UPDATE per row, vs one set-based UPDATE):

Messages
Cursor:    33333 rows in 15466 ms
Set-based: 33333 rows in 49 ms

The cursor took 15.5 seconds; the single UPDATE took 49 milliseconds, about 300 times faster. The cursor executes 33,333 separate statements, each with its own overhead, logging and locking. The set-based UPDATE lets SQL Server process all rows in one optimised operation.

@@FETCH_STATUS after the last row

DECLARE @Name VARCHAR(100);
DECLARE OneCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT TOP (1) EmployeeName FROM dbo.CursorEmployeeDemo ORDER BY EmployeeId;

OPEN OneCursor;
FETCH NEXT FROM OneCursor INTO @Name;
PRINT 'After 1st FETCH: @@FETCH_STATUS = ' + CAST(@@FETCH_STATUS AS VARCHAR(5)) + ', name = ' + @Name;
FETCH NEXT FROM OneCursor INTO @Name;
PRINT 'After 2nd FETCH: @@FETCH_STATUS = ' + CAST(@@FETCH_STATUS AS VARCHAR(5));
CLOSE OneCursor;
DEALLOCATE OneCursor;
Messages
After 1st FETCH: @@FETCH_STATUS = 0, name = Rahul Sharma
After 2nd FETCH: @@FETCH_STATUS = -1

The cursor has one row: the first FETCH returns it (0), the second finds nothing (-1), and that ends a WHILE @@FETCH_STATUS = 0 loop. Note that @@FETCH_STATUS is global to the connection: it reflects the last FETCH on any cursor, so check it immediately after each FETCH.

Common mistake: forgetting CLOSE and DEALLOCATE

A cursor declared GLOBAL (the default unless the database option says otherwise) stays alive for the whole connection. If a script fails before reaching DEALLOCATE, running it again fails:

DECLARE LeakyCursor CURSOR GLOBAL FOR SELECT EmployeeId FROM dbo.CursorEmployeeDemo;
OPEN LeakyCursor;
GO
-- the script is run again without CLOSE / DEALLOCATE
DECLARE LeakyCursor CURSOR GLOBAL FOR SELECT EmployeeId FROM dbo.CursorEmployeeDemo;
Messages
Msg 16915, Level 16, State 1
A cursor with the name 'LeakyCursor' already exists.
SELECT CURSOR_STATUS('global', 'LeakyCursor') AS LeakyCursorStatus;   -- 1 = open with rows
CLOSE LeakyCursor;
DEALLOCATE LeakyCursor;
SELECT CURSOR_STATUS('global', 'LeakyCursor') AS AfterDeallocate;     -- -3 = does not exist
Output
LeakyCursorStatus
1
AfterDeallocate
-3

Fix: declare cursors as LOCAL (they are removed automatically when the batch or procedure ends), always CLOSE and DEALLOCATE, and in procedures put the cleanup in your error handling as well.

Cursor types: STATIC vs DYNAMIC

Cursor options decide whether the cursor sees changes made to the table after it was opened. Here both cursors are opened, then the salary is changed, then each cursor fetches the row:

DECLARE @Name VARCHAR(100), @Salary DECIMAL(18,2);

DECLARE StaticCur CURSOR LOCAL STATIC FOR
SELECT EmployeeName, Salary FROM dbo.CursorEmployeeDemo WHERE EmployeeName = 'Amit Verma';

DECLARE DynamicCur CURSOR LOCAL DYNAMIC FOR
SELECT EmployeeName, Salary FROM dbo.CursorEmployeeDemo WHERE EmployeeName = 'Amit Verma';

OPEN StaticCur;
OPEN DynamicCur;

UPDATE dbo.CursorEmployeeDemo SET Salary = 99999 WHERE EmployeeName = 'Amit Verma';

FETCH NEXT FROM StaticCur INTO @Name, @Salary;
PRINT 'STATIC  cursor sees: ' + @Name + ' ' + CAST(@Salary AS VARCHAR(20));

FETCH NEXT FROM DynamicCur INTO @Name, @Salary;
PRINT 'DYNAMIC cursor sees: ' + @Name + ' ' + CAST(@Salary AS VARCHAR(20));

CLOSE StaticCur;  DEALLOCATE StaticCur;
CLOSE DynamicCur; DEALLOCATE DynamicCur;
Messages
STATIC  cursor sees: Amit Verma 50000.00
DYNAMIC cursor sees: Amit Verma 99999.00
OptionBehaviourUse when
FAST_FORWARDForward-only, read-only, optimisedThe default choice for reading rows one by one
STATICCopies the result into tempdb at OPEN; doesn't see later changes (it showed the old 50000)You need a stable snapshot or to scroll back and forth
DYNAMICSees all changes made after OPEN (it showed 99999)Rarely; it's the most expensive type
KEYSETFixed set of rows (keys) at OPEN; sees updates to those rows but not new rowsRarely
LOCAL / GLOBALScope: this batch or procedure only, or the whole connectionAlways use LOCAL
SCROLLAllows FETCH PRIOR, FIRST, LAST, ABSOLUTE nWhen you really need to move backwards

When to use a cursor, and when not to

Reasonable usesUse a set-based query instead
Calling a stored procedure once per row (for example EXEC sp_send_dbmail for each customer)Updating or deleting rows that match a condition: UPDATE ... WHERE
Running dynamic SQL per object (each database, table or index in maintenance scripts)Totals and counts: GROUP BY and aggregate functions
Small one-time admin scripts where clarity matters more than speedRunning totals, previous/next row values: window functions, LAG and LEAD
Row-by-row logic that truly depends on the result of the previous row and can't be expressed in SQLCopying or syncing rows between tables: INSERT ... SELECT, MERGE

Advantages and disadvantages

AdvantagesDisadvantages
Row-by-row control, easy to understand for developers used to loopsSlow: 300 times slower than the set-based UPDATE in our test
Can call procedures or dynamic SQL for each rowUses more memory, tempdb (STATIC) and locks for longer
Can print or log progress per rowMore code, and resource leaks if not closed and deallocated
Sometimes the only way to handle per-row side effectsLong-running cursors can block other users

Interview questions

1. What is a cursor in SQL Server?

A database object that lets you process the rows of a SELECT result one at a time, using DECLARE, OPEN, FETCH, CLOSE and DEALLOCATE.

2. What does @@FETCH_STATUS return?

The status of the last FETCH on the connection: 0 when a row was fetched, -1 when there are no more rows, -2 when the fetched row no longer exists.

3. What is the difference between CLOSE and DEALLOCATE?

CLOSE releases the current result set and its locks, but the cursor definition remains and can be opened again. DEALLOCATE removes the cursor completely, freeing its name.

4. Why are cursors slow?

They process one row per statement, so the per-statement overhead (execution, logging, locking) is paid for every row, instead of once for the whole set. In our test, 33,333 rows took 15.5 seconds with a cursor and 49 ms with one UPDATE.

5. What is the fastest type of cursor?

LOCAL FAST_FORWARD: forward-only and read-only, with performance optimisations.

6. What is the difference between a STATIC and a DYNAMIC cursor?

A STATIC cursor works on a copy of the result taken at OPEN and doesn't see later changes. A DYNAMIC cursor reflects all inserts, updates and deletes made while it's open.

7. What are the alternatives to cursors?

Set-based statements (UPDATE/DELETE/INSERT ... SELECT with WHERE and JOIN), window functions, CTEs, MERGE, and when row-by-row processing is really needed, a WHILE loop over a temp table with a key, or doing the loop in application code.

Summary

  • A cursor processes a query's rows one at a time: DECLARE, OPEN, FETCH, loop while @@FETCH_STATUS = 0, CLOSE, DEALLOCATE.
  • Use LOCAL FAST_FORWARD by default, and always CLOSE and DEALLOCATE.
  • STATIC cursors use a snapshot; DYNAMIC cursors see live changes.
  • Set-based SQL is much faster: 49 ms vs 15.5 seconds for 33,333 rows in our test.
  • Use cursors only for genuinely per-row work, such as calling a procedure for each row.

Related: Views, temporary tables and dynamic SQL.