Oracle 有条件地打开不同的游标并执行相同的操作
根据用户输入,我的程序需要打开不同的游标,但执行相同的操作。由于游标将从不同的表中获取数据,因此我无法将查询合并到一个表中,也无法使用参数化游标。我们是否可以在不使用refcursor的情况下执行以下操作Oracle 有条件地打开不同的游标并执行相同的操作,oracle,plsql,cursor,Oracle,Plsql,Cursor,根据用户输入,我的程序需要打开不同的游标,但执行相同的操作。由于游标将从不同的表中获取数据,因此我无法将查询合并到一个表中,也无法使用参数化游标。我们是否可以在不使用refcursor的情况下执行以下操作 DECLARE p_cond NUMBER; CURSOR c1 IS SELECT 'a' txt FROM dual; -- table A CURSOR c2 IS SELECT 'b' txt FROM dua
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;
/
谢谢 我假设您的select查询将始终返回具有相同结构的记录集,无论它是从表A还是表B中进行选择。如果是这种情况,使用ref游标将很有帮助 如果select查询也可能返回结构不同的记录集,则 您必须使用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;
谢谢你的建议,但我尽量避免使用refcursor,因为我的查询非常复杂且成本很高。最后,我通过使用union(我完全忘记了这一点)来组合查询。