内循环中的动态光标。多个游标

时间:2014-09-24 14:15:34

标签: oracle loops cursor

请考虑以下事项。

declare

v_name     person.name%TYPE;
v_surname  person.surname%TYPE;

cursor department_cursor is
    select * from department;

cursor person_cursor is 
    select * from person 
    where nvl(name, '')   = nvl(v_name, '');    

begin
  open department_cursor;  
  open person_cursor;
  for department_row in department_cursor loop

    v_name  := department_row.name;
    v_surname  := department_row.surname;

    for person_row in person_cursor loop
        DBMS_OUTPUT.PUT_LINE('I got here:'||person_row.p_id);
    end loop;   

  end loop;
  close person_cursor;
  close department_cursor;
end;
/

不要试图理解它的作用。它只是实际代码的剥离/破坏版本。 果汁仍然存在。我想做的是有两个游标。第二个游标是动态的,它取决于第一个游标返回的行。

以上结果为ORA-06511: PL/SQL: cursor already open

1 个答案:

答案 0 :(得分:2)

问题是你有读取的行

open department_cursor;  
open person_cursor;

以后你还有其他行

for department_row in department_cursor loop

for person_row in person_cursor loop

后面的行试图打开已经打开的游标。

我建议你将代码重写为:

declare
  v_name     person.name%TYPE;
  v_surname  person.surname%TYPE;

  cursor department_cursor is
    select * from department;

  cursor person_cursor is 
    select * from person 
    where nvl(name, '')   = nvl(v_name, '');    
begin
  for department_row in department_cursor loop
    v_name  := department_row.name;
    v_surname  := department_row.surname;

    for person_row in person_cursor loop
        DBMS_OUTPUT.PUT_LINE('I got here:'||person_row.p_id);
    end loop;   
  end loop;
end;

分享并享受。