dynamic table name without using cursors

本秂侑毒 提交于 2021-02-08 07:41:05

问题


I want to use dynamic table name within a for loop. I understand that there are solutions to this problems by using cursors. But I was wondering if there is a solution without cursor as my current code has generic for loop (implicit cursors) and I wanted to know if I can retain it the same way without going for explicit cursors.

What works for me right now is:

BEGIN 
for itr in (select var1,var2,var3,var4 from schedule_table)
loop
--work using itr.var1, itr.var2, itr.var3, itr.var4 
end loop
END

and I want to know if there was anyway I can use the same kind of for loop but pass table name to it dynamically. I looked into execute immediate dynamic sql options, but I don't think I would be able to use it within for loop. I just thought of checking this here before I went about redesigning the entire procedure to work with explicit cursors (not a big fan as I fear performance compared to implicit).

Thank You.


回答1:


You can use EXECUTE IMMEDIATE to BULK COLLECT INTO a collection and the loop through that:

Oracle 12c

DECLARE
  TYPE t_rec IS RECORD( fname VARCHAR2(100), lname VARCHAR2(100) );
  TYPE t_tab IS TABLE OF t_rec;
  t t_tab;
  v_table_name VARCHAR2(128) := 'HR.EMPLOYEES';
BEGIN
  EXECUTE IMMEDIATE 'SELECT first_name, last_name FROM ' || v_table_name
    BULK COLLECT INTO t;

  FOR i IN 1 .. t.COUNT LOOP
    DBMS_OUTPUT.PUT_LINE( t(i).fname || ' ' || t(i).lname );
  END LOOP;
END;
/

Note: In Oracle 10/11 you will need to create the collection type in the SQL scope. In Oracle 12, you can declare it in the PL/SQL scope.



来源:https://stackoverflow.com/questions/42894080/dynamic-table-name-without-using-cursors

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