Plsql 同一数据集的2个参考游标
你能解释一下如何为同一个结果集创建两个游标吗? 我有 如下所示:Plsql 同一数据集的2个参考游标,plsql,Plsql,你能解释一下如何为同一个结果集创建两个游标吗? 我有 如下所示: declare emp_id_c1 number; emp_id_c2 number; c1 sys_refcursor; c2 sys_refcursor; begin open c1 for with x as select emp_id from emp; c2 := c1; loop fetch c1 into emp_id_c1; dbms_output.put
declare
emp_id_c1 number;
emp_id_c2 number;
c1 sys_refcursor;
c2 sys_refcursor;
begin
open c1 for with x as select emp_id from emp;
c2 := c1;
loop
fetch c1 into emp_id_c1;
dbms_output.put_line('some');
loop
fetch c2 into emp_id_c2;
dbms_output();
exit when c2%notfound;
end loop;
exit when c1%notfound;
end loop;
end;
declare
val1 number;
val2 number;
cursor c1 is
select column1, column2
from table1 t1 join table2 t2 on t1.column1 = t2.column2
where <condition1> and <condition2>;
begin
open c1;
loop
fetch c1 into val1, val2;
exit when c1%notfound;
dbms_output.put_line('some text to output');
end loop;
end;
谢谢你我不知道你的目标是什么,但我知道当你想用两个游标进行嵌套循环时,你犯错误的概率是99%。如果需要比较两个游标中的数据,请将它们组合成一个SQL查询并进行处理。主要原因是性能。与纯SQL相比,嵌套循环可以将性能降低100倍。例如,对于基于查询的游标
select column1 from table1 where <condition1>
写
在第一个循环中:
open c1 for ...
loop
fetch c1 into emp_id_c1;
...
open c2 for ...
loop
...
end loop; -- inner loop
end loop; -- outer loop
根据您对同一数据集提出的问题,要填充两个不同的光标,然后再填充光标,则您遵循的是正确的方法:
declare
emp_id_c1 number;
emp_id_c2 number;
c1 sys_refcursor;
c2 sys_refcursor;
begin
open c1 for
select EmpID from Table1;
c2 := c1;
loop
fetch c1 into emp_id_c1;
dbms_output.put_line('Cusrsor 1 data');
loop
fetch c2 into emp_id_c2;
dbms_output.put_line('Cusrsor 2 data');
dbms_output.put_line(emp_id_c2);
exit when c2%notfound;
end loop;
exit when c1%notfound;
end loop;
end;
Ref游标定义为“按引用”,因此c1和c2是相同的。另外,游标是结果集的规范,所以我不确定一个结果集的两个游标是什么意思。你想解决什么问题?基于Scott的示例模式(EMP和DEPT表),你能解释一下吗?嗨,我想在同一个数据集上迭代2次,并使用refcursor,如果c1和c2是相同的东西,我怎么能将这两个对象作为具有相同数据集的单独对象c1和c2?有没有办法将值从c1传递到c2?谢谢这是一次迭代,我需要对同一组数据进行两次迭代。我可以通过声明一种类型的记录来实现这一点。我想知道如何将另一个游标c2声明为同一组数据上c12迭代的单独对象?除非是家庭作业,否则我看不出这有什么实际意义。但我会在答案中添加您想要的内容。
open c2 for ...
open c1 for ...
loop
fetch c1 into emp_id_c1;
...
open c2 for ...
loop
...
end loop; -- inner loop
end loop; -- outer loop
declare
emp_id_c1 number;
emp_id_c2 number;
c1 sys_refcursor;
c2 sys_refcursor;
begin
open c1 for
select EmpID from Table1;
c2 := c1;
loop
fetch c1 into emp_id_c1;
dbms_output.put_line('Cusrsor 1 data');
loop
fetch c2 into emp_id_c2;
dbms_output.put_line('Cusrsor 2 data');
dbms_output.put_line(emp_id_c2);
exit when c2%notfound;
end loop;
exit when c1%notfound;
end loop;
end;