rajeemcariazo
rajeemcariazo

Reputation: 2524

Loop through an explicit cursor in Oracle

How can I loop through an implicit cursor which is created, for example, from a query?

Here is the sample code:

SERVEROUTPUT on;

DECLARE      
  TYPE ref_cursor IS REF CURSOR;
  cur REF_CURSOR;

BEGIN
  OPEN cur FOR 'SELECT i.item_no, 
                       i.item_descr 
                  FROM ITEMS i 
                 WHERE i.item_no in (1,2,3)';

  ... loop statement to print all item descriptions?

END;

Upvotes: 7

Views: 14075

Answers (2)

Dave Costa
Dave Costa

Reputation: 48111

Here's how to do it allowing for dynamic SQL. You can build the query string up in code however needed (usual warnings about SQL injection apply).

DECLARE      
  TYPE ref_cursor IS REF CURSOR;
  cur REF_CURSOR;

  d_item_no  items.item_no%TYPE;
  d_item_descr  items.item_descr%TYPE;

BEGIN
  OPEN cur FOR 'SELECT i.item_no, 
                       i.item_descr 
                  FROM ITEMS i 
                 WHERE i.item_no in (1,2,3)';
  LOOP
    FETCH cur INTO d_item_no, d_item_descr;
    EXIT WHEN cur%NOTFOUND;
    dbms_output.put_line( d_item_no||' '||d_item_descr );
  END LOOP;

  CLOSE cur;
END;
/

Upvotes: 10

OMG Ponies
OMG Ponies

Reputation: 332531

I'm not up on the 11g changes, but this should work:

BEGIN

  FOR cur IN (SELECT i.item_no, 
                     i.item_descr 
                FROM ITEMS i 
               WHERE i.item_no in (1,2,3))
  LOOP
    DBMS_OUTPUT.PUT_LINE('Row: '|| cur.item_no ||' '|| cur.item_descr);
  END LOOP;

END;

Upvotes: 8

Related Questions