Introduction

This article is all about cursors in SQL Server.

Cursors

In order to work with a cursor we need to perform some steps in the following order
  1. Declare cursor
  2. Open cursor
  3. Fetch row from the cursor
  4. Process fetched row
  5. Close cursor
  6. Deallocate cursor

Types of Cursors

Base Table Cursors
Static Cursors
Forward-only Cursors
Keyset-driven Cursors
FETCH command also having various types,
  1. NEXT
  2. PRIOR
  3. FIRST
  4. LAST
  5. ABSOLUTE
  6. RELATIVE
E.g.: - For Forward-only Cursors
  1. DECLARE @Complaint_Id Int
  2. DECLARE Merge_Cursor CURSOR FAST_FORWARD FOR
  3. Select Cust_CMP_Id from CR_Complaint_Master
  4. Open Merge_Cursor
  5. FETCH NEXT FROM Merge_Cursor INTO @Complaint_Id
  6. WHILE @@FETCH_STATUS = 0
  7. BEGIN
  8. UPDATE CR_Complaint_Master
  9. SET
  10. Cust_CMP_State= 'Karnataka'
  11. WHERE
  12. Cust_CMP_Id = @Complaint_Id
  13. FETCH NEXT FROM Merge_Cursor INTO @Complaint_Id
  14. END
  15. CLOSE Merge_Cursor
  16. DEALLOCATE Merge_Cursor
Advantages of Cursor
Disadvantages of Cursor
Here are some alternatives to using a cursor,