SoFunction
Updated on 2025-04-07

How to use cursors (cursors) in SQL Server database and complete examples

In SQL Server databases, a cursor is a database object used to process result sets row by row. Here is how to use cursors:

1. Declare cursor

First, use the DECLARE statement to declare the cursor and specify the result set to be processed.

DECLARE cursor_name CURSOR FOR
SELECT column1, column2
FROM table_name
WHERE condition;

2. Open the cursor

Use the OPEN statement to open the cursor to start processing the result set.

OPEN cursor_name;

3. Obtain data

Use the FETCH statement to get the data in the cursor line by line.

FETCH NEXT FROM cursor_name INTO @variable1, @variable2;

4. Process data

Process each row of data in a loop until there is no more data to be retrieved.

WHILE @@FETCH_STATUS = 0
BEGIN
    -- Logic for processing data
    PRINT @variable1 + ' ' + @variable2;
    -- Get the next line of data
    FETCH NEXT FROM cursor_name INTO @variable1, @variable2;
END;

5. Close the cursor

After processing the data, use the CLOSE statement to close the cursor.

CLOSE cursor_name;

6. Release the cursor

Finally, use the DEALLOCATE statement to release the cursor resource.

DEALLOCATE cursor_name;

Complete example
Here is a complete cursor usage example:

DECLARE @EmployeeID INT;
DECLARE @EmployeeName NVARCHAR(50);
DECLARE employee_cursor CURSOR FOR
SELECT EmployeeID, EmployeeName
FROM Employees
WHERE DepartmentID = 1;
OPEN employee_cursor;
FETCH NEXT FROM employee_cursor INTO @EmployeeID, @EmployeeName;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Employee ID: ' + CAST(@EmployeeID AS NVARCHAR) + ', Employee Name: ' + @EmployeeName;
    FETCH NEXT FROM employee_cursor INTO @EmployeeID, @EmployeeName;
END;
CLOSE employee_cursor;
DEALLOCATE employee_cursor;

Things to note
Cursors may affect performance when processing large data sets, and should be avoided when using them in scenarios where high performance is required.

When using cursors, be sure to close and release the cursor after the operation is finished to avoid resource leakage.

This is the article about the detailed explanation of the usage methods and examples of cursors in SQL Server database. For more information about the usage of cursors in SQL Server, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!