Bird
0
0

Given the following SQL cursor code snippet, what will be the output?

medium📝 query result Q13 of 15
SQL - Stored Procedures and Functions
Given the following SQL cursor code snippet, what will be the output?
DECLARE @Name VARCHAR(50);
DECLARE name_cursor CURSOR FOR SELECT Name FROM Employees WHERE Department = 'Sales';
OPEN name_cursor;
FETCH NEXT FROM name_cursor INTO @Name;
WHILE @@FETCH_STATUS = 0
BEGIN
  PRINT @Name;
  FETCH NEXT FROM name_cursor INTO @Name;
END
CLOSE name_cursor;
DEALLOCATE name_cursor;

Assuming the Employees table has Sales department names: 'Alice', 'Bob', 'Carol'.
AOnly 'Alice' is printed
BSyntax error due to missing FETCH
CNo output because cursor is not opened
DAlice Bob Carol (each printed on a new line)
Step-by-Step Solution
Solution:
  1. Step 1: Understand cursor fetch loop

    The cursor fetches each row where Department = 'Sales'. It prints the @Name variable for each fetched row.
  2. Step 2: Identify the printed names

    Since the table has 'Alice', 'Bob', and 'Carol' in Sales, all three names will be printed one by one.
  3. Final Answer:

    Alice Bob Carol (each printed on a new line) -> Option D
  4. Quick Check:

    Cursor prints all fetched rows [OK]
Quick Trick: Cursor loops print all fetched rows until none left [OK]
Common Mistakes:
  • Assuming only first row prints
  • Forgetting to open cursor
  • Confusing fetch status check

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes