Loop through an explicit cursor in Oracle

ぐ巨炮叔叔 提交于 2019-12-21 11:31:57

问题


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;

回答1:


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;
/



回答2:


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;


来源:https://stackoverflow.com/questions/5878145/loop-through-an-explicit-cursor-in-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!