Cursor Practice Exercise: Worked Solution
Objective: Explain a complete cursor loop and its expected results.
Run this complete script in a fresh SQL Server test session. If you already ran the exercise setup in that session, omit the CREATE TABLE and INSERT portion.
CREATE TABLE #Employees (
EmployeeID int NOT NULL PRIMARY KEY,
EmployeeName nvarchar(50) NOT NULL
);
INSERT INTO #Employees (EmployeeID, EmployeeName)
VALUES (101, N'Ana'), (102, N'Ben'), (103, N'Chen');
DECLARE employee_cursor CURSOR
LOCAL FAST_FORWARD
FOR SELECT EmployeeID, EmployeeName
FROM #Employees
ORDER BY EmployeeID;
DECLARE @EmployeeID int, @EmployeeName nvarchar(50);
OPEN employee_cursor;
FETCH NEXT FROM employee_cursor INTO @EmployeeID, @EmployeeName;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT CONCAT(@EmployeeID, N': ', @EmployeeName);
FETCH NEXT FROM employee_cursor INTO @EmployeeID, @EmployeeName;
END;
CLOSE employee_cursor;
DEALLOCATE employee_cursor;
DROP TABLE #Employees;Why it works
The ordered SELECT makes the teaching sequence deterministic. The first FETCH occurs before the loop; each iteration processes only a successful result and fetches again before the next test. The two INTO variables match the two selected columns. CLOSE and DEALLOCATE perform distinct cleanup steps.
An empty result produces no employee messages because the first FETCH is unsuccessful. In production code, add error-path cleanup such as the pattern in Lesson 10. This page does not inspect submitted answers or award credit.