SQL Server 2025 · Module 6

Cursor Declaration and FETCH: Practice Exercise

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

  1. Declare employee_cursor as LOCAL FAST_FORWARD.
  2. Select EmployeeID and EmployeeName in EmployeeID order.
  3. Open it and fetch into compatible variables.
  4. Print each employee only after a successful fetch.
  5. 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

CriterionPoints
Explicit scope, type, columns, and order5
OPEN and matching FETCH INTO variables5
Initial fetch, guarded loop, and advancing fetch5
CLOSE, DEALLOCATE, and table cleanup5

View the worked solution and explanation

Return to Lesson 8