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
| Step | What it does |
|---|---|
DECLARE ... CURSOR FOR SELECT ... | Defines the cursor and the query it will walk through |
OPEN | Runs the query and positions the cursor before the first row |
FETCH NEXT ... INTO @variables | Moves to the next row and copies its columns into variables |
@@FETCH_STATUS | 0 = a row was fetched; -1 = no more rows; -2 = the row was deleted |
CLOSE | Releases the result set and its locks; the cursor can be reopened |
DEALLOCATE | Removes 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
| EmployeeId | EmployeeName | Department | Salary | City |
|---|---|---|---|---|
| 1 | Rahul Sharma | IT | 80000.00 | Indore |
| 2 | Amit Verma | HR | 50000.00 | Bhopal |
| 3 | Priya Singh | IT | 90000.00 | Pune |
| 4 | Neha Jain | Finance | 65000.00 | Indore |
| 5 | Vikas Patel | IT | 75000.00 | Mumbai |
| 6 | Ankit Gupta | HR | 55000.00 | Indore |
| 7 | Sneha Mishra | Finance | 70000.00 | Bhopal |
| 8 | Rohit Sharma | IT | 95000.00 | Pune |
| 9 | Pooja Verma | HR | 60000.00 | Mumbai |
| 10 | Karan Mehta | Finance | 85000.00 | Indore |
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
How it works:
- The variables must match the cursor's SELECT columns in number, order and type, because
FETCH ... INTOcopies them by position. - The first FETCH comes before the loop. The loop checks
@@FETCH_STATUSand 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_FORWARDis 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
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
| EmployeeId | EmployeeName | Department | Salary | City |
|---|---|---|---|---|
| 1 | Rahul Sharma | IT | 88000.00 | Indore |
| 3 | Priya Singh | IT | 99000.00 | Pune |
| 5 | Vikas Patel | IT | 82500.00 | Mumbai |
| 8 | Rohit Sharma | IT | 104500.00 | Pune |
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';
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):
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;
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;
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
| 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;
| Option | Behaviour | Use when |
|---|---|---|
FAST_FORWARD | Forward-only, read-only, optimised | The default choice for reading rows one by one |
STATIC | Copies 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 |
DYNAMIC | Sees all changes made after OPEN (it showed 99999) | Rarely; it's the most expensive type |
KEYSET | Fixed set of rows (keys) at OPEN; sees updates to those rows but not new rows | Rarely |
LOCAL / GLOBAL | Scope: this batch or procedure only, or the whole connection | Always use LOCAL |
SCROLL | Allows FETCH PRIOR, FIRST, LAST, ABSOLUTE n | When you really need to move backwards |
When to use a cursor, and when not to
| Reasonable uses | Use 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 speed | Running 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 SQL | Copying or syncing rows between tables: INSERT ... SELECT, MERGE |
Advantages and disadvantages
| Advantages | Disadvantages |
|---|---|
| Row-by-row control, easy to understand for developers used to loops | Slow: 300 times slower than the set-based UPDATE in our test |
| Can call procedures or dynamic SQL for each row | Uses more memory, tempdb (STATIC) and locks for longer |
| Can print or log progress per row | More code, and resource leaks if not closed and deallocated |
| Sometimes the only way to handle per-row side effects | Long-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_FORWARDby 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.