Practice and review
Cursor Declaration and FETCH: Practice Exercise
Objective: Build a complete, read-only cursor loop with cleanup.
Use a SQL Server 2025 test session. This exercise is self-assessed: no answer is submitted to a tutor and no automatic credit is awarded.
Practice data
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');
Your task
- Declare employee_cursor as LOCAL FAST_FORWARD.
- Select EmployeeID and EmployeeName in EmployeeID order.
- Open it and fetch into compatible variables.
- Print each employee only after a successful fetch.
- Close and deallocate the cursor, then drop the temporary table.
Keep declaration and use in one batch. The expected messages are 101: Ana, 102: Ben, and 103: Chen, each once. As an extension, repeat with an empty table and confirm that no employee is processed.
Self-assessment rubric
| Criterion | Points |
|---|---|
| Explicit scope, type, columns, and order | 5 |
| OPEN and matching FETCH INTO variables | 5 |
| Initial fetch, guarded loop, and advancing fetch | 5 |
| CLOSE, DEALLOCATE, and table cleanup | 5 |