Cursors In SQL Server

Estimated study time: 11 minutes. Process a result set one row at a time.

A cursor lets you step through a result set row by row, rather than operating on the whole set at once. SQL is set-based by nature, so cursors are the exception, not the default tool.

Basic Cursor Syntax

DECLARE @EmpName VARCHAR(100);

DECLARE emp_cursor CURSOR FOR
SELECT EmpName FROM Employees;

OPEN emp_cursor;
FETCH NEXT FROM emp_cursor INTO @EmpName;

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @EmpName;
    FETCH NEXT FROM emp_cursor INTO @EmpName;
END;

CLOSE emp_cursor;
DEALLOCATE emp_cursor;

Cursor Types

SQL Server supports several cursor types, including STATIC (a snapshot, insensitive to later changes), DYNAMIC (reflects changes as you scroll), and FORWARD_ONLY (can only move forward, and is the fastest of the three).

Why Cursors Are Usually a Last Resort

Cursors process one row at a time, which is far slower than a set-based UPDATE, INSERT, or SELECT working on the whole table at once. Most row-by-row logic can be rewritten as a single set-based statement.

💡 Tip: Before reaching for a cursor, ask whether a JOIN, CASE expression, or window function could achieve the same result in one set-based statement.

From Cursor to Set-Based: A Worked Rewrite

Imagine a rule that gives Sales staff a 10% raise and everyone else 5%. A first attempt often loops through employees one at a time:

DECLARE @Id INT, @Dept VARCHAR(50);

DECLARE raise_cursor CURSOR LOCAL FAST_FORWARD FOR
    SELECT EmpId, Department FROM Employees;

OPEN raise_cursor;
FETCH NEXT FROM raise_cursor INTO @Id, @Dept;

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @Dept = 'Sales'
        UPDATE Employees SET Salary = Salary * 1.10 WHERE EmpId = @Id;
    ELSE
        UPDATE Employees SET Salary = Salary * 1.05 WHERE EmpId = @Id;

    FETCH NEXT FROM raise_cursor INTO @Id, @Dept;
END;

CLOSE raise_cursor;
DEALLOCATE raise_cursor;

This runs a separate UPDATE for every employee, each with its own lookup and logging. The same result takes one statement when the decision moves into a CASE expression:

UPDATE Employees
SET Salary = Salary * CASE WHEN Department = 'Sales' THEN 1.10 ELSE 1.05 END;

The set-based version lets the query optimiser plan the whole job at once. On a large table the difference is dramatic, and the code is shorter and easier to review. Similar rewrites work for running totals, using SUM() OVER (ORDER BY ...), and for "previous row" comparisons, using LAG().

When a Cursor Is a Reasonable Choice

Cursors are not banned; they are a tool for jobs that are truly row-by-row:

  • Calling a stored procedure for each row, for example EXEC dbo.SendWelcomeEmail @EmpId = @Id;, when the procedure cannot accept a set of rows.
  • Administrative scripts that loop over databases or tables to run maintenance commands built with dynamic SQL.
  • Processing in small batches where each step depends on the result of the previous one.

When you do use one, the options matter. LOCAL limits the cursor to the current batch or procedure, avoiding name clashes, since cursors are global by default unless the database setting says otherwise. FAST_FORWARD creates a forward-only, read-only cursor with performance optimisations, which is the right default for simple loops.

Reading @@FETCH_STATUS correctly

ValueMeaning
0The fetch succeeded and a row was returned
-1The fetch failed or there are no more rows
-2The row has been deleted since the cursor was opened (keyset cursors)

Cursor Mistakes and the MySQL Difference

  • Missing the second FETCH. If you forget the FETCH NEXT inside the loop, @@FETCH_STATUS never changes and the loop runs forever.
  • Skipping cleanup. Always CLOSE and DEALLOCATE, otherwise a global cursor stays allocated and the next run fails with "cursor already exists".
  • Wrapping the whole loop in one huge transaction. Locks build up row after row and block other users. Commit in sensible batches or rewrite as a set operation.
  • Using a cursor to read data for an application. Return a normal result set and let the application iterate over it.

MySQL also has cursors, but only inside stored procedures, functions and triggers. They are always read-only and forward-only, and instead of @@FETCH_STATUS you declare a CONTINUE HANDLER FOR NOT FOUND that sets a "done" variable to end the loop. The advice is the same: reach for a set-based statement first.

Ready to go beyond the basics?

Get hands-on training, live mentorship, and placement support with Uncodemy's Data Analytics Course.

Explore Data Analytics Course →