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:
- Declare a variable (
@name
) to store data from the cursor. - Declare the cursor (
cur
) for aSELECT
query. - Open the cursor.
- Fetch the first row into the variable.
- Use a
WHILE
loop to iterate through all rows. - 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.