SQL Cursor Example

DECLARE @name VARCHAR(50);
 
DECLARE cur CURSOR FOR 
SELECT name FROM Employees;
 
OPEN cur;
FETCH NEXT FROM cur INTO @name;
 
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @name;
    FETCH NEXT FROM cur INTO @name;
END;
 
CLOSE cur;
DEALLOCATE cur;

Steps Explained:

  1. Declare a variable (@name) to store data from the cursor.
  2. Declare the cursor (cur) for a SELECT query.
  3. Open the cursor.
  4. Fetch the first row into the variable.
  5. Use a WHILE loop to iterate through all rows.
  6. Close and deallocate the cursor after use.

When to Use Cursors?

  • When you need to process each row individually.
  • When set-based operations are not possible or too complex.
  • When working with procedural logic inside SQL.

⚠️ Note: Cursors can be slow for large datasets. Try to use set-based operations whenever possible.