2017-05-03 55 views
0

根据用户输入,我的程序需要打开不同的光标,但执行相同的操作。由于游标将从不同的表中获取数据,因此我无法将查询合并为一个,或者使用参数化游标。无论如何,我们可以在不使用refcursor的情况下执行以下操作?有条件地打开不同的光标并执行相同的动作

DECLARE 
    p_cond  NUMBER; 

    CURSOR c1 IS 
     SELECT 'a' txt FROM dual; -- table A 

    CURSOR c2 IS 
     SELECT 'b' txt FROM dual; -- table B 

BEGIN 
    p_cond := 1; 

    FOR tmp IN decode(p_cond, 1, c1, c2) loop -- this of course doesn't work 
     dbms_output.put_line(tmp.txt); 
    END loop; 

END; 
/

谢谢!!

回答

0

我假设您的选择查询将始终返回具有相同结构的记录集,无论它是从表A还是从表B中选择。如果是这种情况,使用ref游标会很有帮助。

如果您的选择查询可能返回结构上不同的记录集,那么 您将不得不使用dbms_sql。

create table a (x varchar2(20)) ; 
create table b (x varchar2(20)) ; 
insert into a values('A') ; 
insert into b values('B') ; 

DECLARE 
    p_cond  NUMBER; 

    Type cur is ref cursor return a%rowtype; 
    c cur ; 
    var c%rowtype ; 
BEGIN 
    p_cond := 0; 

    If p_cond = 1 then 
    Open c for SELECT 'a' FROM dual; 
    else 
     Open c for SELECT 'b' FROM dual; 
    end if ; 

    loop 
    fetch c into var ; 
    exit when c%notfound ; 
    dbms_output.put_line(var.x) ; 
    end loop; 

END; 
+0

感谢您的建议,但我尽量避免refcursor,因为我的查询相当复杂且成本高。最后我设法通过使用联合来结合查询(我已经完全忘记了)。 – noobie

相关问题