Skip to main content

REF CURSOR (Cursor Variables) πŸŽžοΈπŸ”€

Mentor's Note: A standard cursor is like a "Hardcoded Channel" on a TV. A REF CURSOR is like a "Variable Channel"β€”it can point to different queries at different times. It allows you to pass a whole result set from a Procedure to an Application (like Java or Python). πŸ’‘


🌟 The Scenario: The Multi-Menu Restaurant πŸ½οΈβ€‹

Imagine a waiter with a tablet.

  • At 8 AM, the tablet shows the Breakfast Menu.
  • At 1 PM, the same tablet shows the Lunch Menu.
  • The tablet (The REF CURSOR) stays the same, but the List of Items (The Query) changes based on the time. βœ…

πŸ’» 1. The Basic Syntax​

We use SYS_REFCURSOR (a built-in type) for the most flexibility.

DECLARE
-- 1. Create the Cursor Variable
v_cursor SYS_REFCURSOR;
v_name employees.first_name%TYPE;
v_choice NUMBER := 1; -- 1 for Emp, 2 for Dept
BEGIN
-- 2. Open it for DIFFERENT queries based on logic
IF v_choice = 1 THEN
OPEN v_cursor FOR SELECT first_name FROM employees;
ELSE
OPEN v_cursor FOR SELECT department_name FROM departments;
END IF;

-- 3. Fetch as usual
LOOP
FETCH v_cursor INTO v_name;
EXIT WHEN v_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Result: ' || v_name);
END LOOP;

CLOSE v_cursor;
END;

πŸ’» 2. Passing Cursors between Subprograms πŸ“€β€‹

This is the #1 use case for REF CURSORS in professional Oracle apps.

-- Procedure that "prepares" the data
CREATE OR REPLACE PROCEDURE get_staff_data(p_out_cursor OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_out_cursor FOR SELECT first_name FROM employees;
END;
/

πŸ›‘οΈ 3. Why use REF CURSOR? (Architect's Note)​

  1. Abstraction: Your Web Application doesn't need to know the complex SQL logic. It just calls a procedure and receives a "Bag of Data" (the REF CURSOR).
  2. Flexibility: One variable can handle many different query structures.
  3. Decoupling: You can change the SQL inside the database without touching your Java/Python application code! ⚑

πŸ“Š Summary Table​

FeatureStatic CursorREF CURSOR
LogicHardcoded QueryDynamic Query
PassingCannot be passed ❌Can be passed OUT βœ…
TypeConstantVariable

πŸ“ˆ Learning Path​

πŸ“ Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
πŸ“ Address
2/66 Faram Street, Rustompura
Surat – 395002, Gujarat, India
πŸ“ž Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition β€” Areas We Serve in Surat

Adajanβ€’Althanβ€’Amroliβ€’Athwaβ€’Athwalinesβ€’Bhagalβ€’Bhatarβ€’Bhestanβ€’Canal Roadβ€’Chowkβ€’Citylightβ€’Dumasβ€’Gaurav Pathβ€’Ghod Dod Roadβ€’Haziraβ€’Jahangirpuraβ€’Kamrejβ€’Kapodraβ€’Katargamβ€’Limbayatβ€’Magdallaβ€’Majura Gateβ€’Mota Varachhaβ€’Nanpuraβ€’New Citylightβ€’Olpadβ€’Palβ€’Pandesaraβ€’Parle Pointβ€’Piplodβ€’Punaβ€’Randerβ€’Ring Roadβ€’Rustampuraβ€’Sachinβ€’Salabatpuraβ€’Sarthanaβ€’Sosyo Circleβ€’Udhnaβ€’Varachhaβ€’Ved Roadβ€’Vesuβ€’VIP Road
πŸ“ž Call SirπŸ’¬ WhatsApp Sir