Oracle中两个不同SQL的单个游标

时间:2018-02-22 03:11:22

标签: oracle

我有一个场景,我想将光标用于两个不同的sql。

create or replace procedure(p_load_type in number)
    as
    create cursor prod_cur
    is
    /* This is the 1st SQL*/
    select product_id,
           product_name
        from Test_product;
    prod_rec     prod_cur%rowtype;

/* here is the second sql that i want cursor open for this  when p_load_type=2
select product_id,
       product_name
    from Test_product tp,
         Test_delta_cases tdc
     where tp.product_id=tdc.product_id;*/
begin
if p_load_type=1 then /* opening for 1st sql*/
open prod_cur
elsif p_load_type=2 then /* opening for 2nd sql*/ 
open prod_cur
end if;
loop

some logic............

end loop;

end;     

1 个答案:

答案 0 :(得分:2)

请使用格式设置格式化问题中的代码。无论如何,您可以使用REF CURSORS,例如

SQL> create or replace
  2  procedure P(p_type int ) is
  3    rc sys_refcursor;
  4
  5    cursor c_template is select 1 x, 1 y from dual;
  6    l_rows c_template%rowtype;
  7
  8  begin
  9    if p_type = 1 then
 10      open rc for select empno, deptno from scott.emp;
 11    else
 12      open rc for select empno, sal from scott.emp;
 13    end if;
 14
 15    loop
 16      fetch rc into l_rows;
 17      exit when rc%notfound;
 18      dbms_output.put_line(l_rows.x||','||l_rows.y);
 19    end loop;
 20  end;
 21  /

Procedure created.

SQL> set serverout on
SQL> exec p(1);
7369,20
7499,30
7521,30
7566,20
7654,30
7698,30
7782,10
7788,20
7839,10
7844,30
7876,20
7900,30
7902,20
7934,10

PL/SQL procedure successfully completed.

SQL> exec p(2);
7369,800
7499,1600
7521,1250
7566,2975
7654,1250
7698,2850
7782,2450
7788,3000
7839,5000
7844,1500
7876,1100
7900,950
7902,3000
7934,1300

PL/SQL procedure successfully completed.