PL/SQL Cursors (The Movie Reel) ποΈΒΆ
Prerequisites: SELECT Statement, PL/SQL Records
Mentor's Note: A
SELECT INTOcan only handle one row. What if you need to process 1,000 employees? You need a Cursor. Think of it as a movie reel: you load the whole movie, but you view it one frame at a time. π‘
π The Scenario: The Bank Queue π¦ΒΆ
Imagine a bank with 100 people waiting. - Goal: Give every person a token. - The Cursor: The teller (The program) looks at the whole line, but calls One Person at a time to the window, processes them, and moves to the next.
π» 1. Implicit Cursors (Automatic)ΒΆ
Oracle opens these automatically for every SQL statement (INSERT, UPDATE, DELETE).
You can check their status using Attributes:
- SQL%FOUND: Did the query find any rows?
- SQL%NOTFOUND: Is it empty?
- SQL%ROWCOUNT: How many rows were affected?
π» 2. Explicit Cursors (The 4-Step Process)ΒΆ
For queries returning multiple rows, you must manage the cursor yourself.
DECLARE
-- 1. DECLARE: Write the query
CURSOR c_emp IS SELECT first_name FROM employees;
v_name employees.first_name%TYPE;
BEGIN
-- 2. OPEN: Execute the query
OPEN c_emp;
LOOP
-- 3. FETCH: Get one row
FETCH c_emp INTO v_name;
EXIT WHEN c_emp%NOTFOUND; -- π Stop at end
DBMS_OUTPUT.PUT_LINE('Employee: ' || v_name);
END LOOP;
-- 4. CLOSE: Free memory
CLOSE c_emp;
END;
ποΈ Architect's Note: Performance & Memory π‘οΈΒΆ
- Closing Cursors: Always
CLOSEyour cursors! Open cursors consume memory on the server. If you leave too many open, you will get the dreadedORA-01000: maximum open cursors exceedederror. - Implicit is Faster: For single-row updates, implicit cursors are actually faster because Oracle performs fewer internal steps.
π¨ Visual Logic: The 4-Step CycleΒΆ
graph LR
A[DECLARE π] --> B[OPEN ποΈ]
B --> C[FETCH π₯]
C --> D{Found?}
D -- Yes --> C
D -- No --> E[CLOSE πͺ]