SQL Server 2025 Cursors: Introduction
Objective: Explain when a Transact-SQL cursor is useful and identify its lifecycle.
A SQL Server cursor lets a Transact-SQL program fetch query results one row at a time. It is useful when a task genuinely requires procedural work for each row. It is not a prerequisite for updating individual rows, and a cursor is not a SQL view.
This module teaches server-side Transact-SQL cursors in SQL Server 2025 (17.x). The statements also exist in earlier supported releases; the purpose of this revision is accurate current practice, not a new cursor syntax unique to 2025.
Start with a set-based solution
SQL is designed to operate on sets. A single UPDATE with a WHERE clause can change selected employees, and a JOIN can match orders to customers without a cursor. Consider a cursor only after checking whether a set-based statement, a window function, or application-side processing expresses the task more clearly.
What you will learn
- Choose between set-based SQL and procedural iteration.
- Distinguish cursor scope, scrolling, updateability, and change visibility.
- Use DECLARE, OPEN, FETCH, CLOSE, and DEALLOCATE in the right order.
- Check fetch status and release resources on success and failure.
- Recognize how concurrent changes affect different cursor choices.
Practice environment
Use a SQL Server 2025 test instance with SQL Server Management Studio or another SQL query client. The website displays examples; it does not run SQL against your database. The examples use temporary tables rather than requiring the old course database or AdventureWorks. Run each complete example in a fresh query session, or clean up its objects before repeating it.
The examples build on the employee practice table introduced in Lesson 2. Keep statements that use LOCAL cursors and variables in the same batch. GO is a client batch separator, not a Transact-SQL statement; inserting it into a sample can end the scope that the sample needs.
The lifecycle
DECLARE → OPEN → FETCH → CLOSE → DEALLOCATE. The first step defines the cursor, the middle steps perform the work, and the final two steps have different cleanup responsibilities. Later lessons explain each step and include a full copyable example.
Continue with when to use a cursor and the practice dataset.