What are the different cursor types available in SQL Server, such as static, dynamic, and forward only, and how do they differ?
Short answer
A static cursor takes a snapshot of the data when it is opened and does not reflect later changes, a dynamic cursor reflects changes made to the underlying data while the cursor is open, and a forward only cursor, which is often the most efficient, only allows moving forward…
Advertisement
AModel answer
A static cursor takes a snapshot of the data when it is opened and does not reflect later changes, a dynamic cursor reflects changes made to the underlying data while the cursor is open, and a forward only cursor, which is often the most efficient, only allows moving forward through the results one row at a time without the ability to go backward.
DECLARE order_cursor CURSOR FORWARD_ONLY STATIC FOR
SELECT OrderId FROM Orders WHERE Status = 'Pending';Real-world example
A batch process uses a forward only static cursor to process pending orders, since it only needs to move through the results once and does not need to see any orders added by other users while it is running.
Likely follow-ups
- Which cursor type generally performs the best in SQL Server?
- When would a dynamic cursor actually be necessary instead of a static one?
Related topics