Oracle cursor with variable columns/tables/criteria

我的未来我决定 提交于 2019-12-25 07:12:24

问题


I need to open a cursor while table name, columns and where clause are varying. The table name etc will be passed as parameter. For example

CURSOR batch_cur
IS
SELECT a.col_1, b.col_1
FROM table_1 a inner join table_2 b 
ON a.col_2 = b.col_2
WHERE a.col_3 = 123

Here, projected columns, table names, join criteria and where clause will be passed as parameters. Once opened, i need to loop through and process each fetched record.


回答1:


You need to use dynamic SQL something like this:

procedure dynamic_proc
    ( p_table_1 varchar2
    , p_table_2 varchar2
    , p_value   number  
    )
is    
    batch_cur sys_refcursor;
begin
    open batch_cur for 
        'select a.col_1, b.col_1
         from ' || p_table_1 || ' a inner join || ' p_table_2 || ' b 
         on a.col_2 = b.col_2
         where a.col_3 = :bind_value1';
      using p_value;
    -- Now fetch data from batch_cur...
end;

Note the use of a bind variable for the data value - very important if you will re-use this many times with different values.




回答2:


From your question i guess you need a dynamic cursor. Oracle provides REFCURSOR for dynamic sql statements. Since your query will be built dynamically you need a refcursor to do that.

 create procedure SP_REF_CHECK(v_col1 number,v_col2 date,v_tab1 number,v_var1 char,v_var2 varchar2)
      is
       Ref_cur is REF CURSOR;
       My_cur Ref_cur;
       My_type  Table_name%rowtype;
       stmt varchar2(500);

  begin
    stmt:='select :1,:2  from :3 where :4=:5';
    open My_cur for stmt   using v_col1,v_col2,v_tab1,v_var1,v_var2;
  loop
    fetch My_cur into My_type;
                //do some processing  //
    exit when My_cur%notfound;
  end loop;
 close My_cur;
end;

Check this link for more http://docs.oracle.com/cd/B10500_01/appdev.920/a96624/11_dynam.htm



来源:https://stackoverflow.com/questions/23052187/oracle-cursor-with-variable-columns-tables-criteria

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