日期:2014-05-17  浏览次数:20744 次

游标相关简单的问题
create or replace procedure test2 is
  cursor v_cur(n number) is
  select num1, num2 from test where num1=n;
  n1 number;
  n2 number;
begin
  open v_cur(1);
  loop
  fetch v_cur
  into n1, n2;
  dbms_output.put_line('n1=' || n1 || ',n2=' || n2);
  exit when v_cur%notfound;
  end loop;
  close v_cur;
end;


数据库执行select num1, num2 from test where num1=1是返回1条记录,但是这个存储过程返回2条重复的记录,是否循坏可能写错了?

------解决方案--------------------
交换这两行顺序:

dbms_output.put_line('n1=' || n1 || ',n2=' || n2);
exit when v_cur%notfound; 
改为:
exit when v_cur%notfound; 
dbms_output.put_line('n1=' || n1 || ',n2=' || n2);。。。
------解决方案--------------------
因为你是先output输出,再判断是否退出循环。
引用楼主 highsea_004 的帖子:
create or replace procedure test2 is
cursor v_cur(n number) is
select num1, num2 from test where num1=n;
n1 number;
n2 number;
begin
open v_cur(1);
loop
fetch v_cur
into n1, n2;
dbms_output.put_line('n1=' || n1 || ',n2=' || n2);
exit when v_cur%notfound;
end loop;
close v_cur;
end;


数据库执行select num1, num2 from test where n…

------解决方案--------------------
SQL code
使用隐式游标岂不是更简单,不存在因为先后导致输出促我的问题。

CREATE OR REPLACE PROCEDURE TEST2 IS
  CURSOR V_CUR(N NUMBER) IS
    SELECT NUM1, NUM2 FROM TEST WHERE num1 = N;
BEGIN
  FOR I IN V_CUR(2) LOOP
    DBMS_OUTPUT.PUT_LINE('n1=' || I.NUM1 || ',n2=' || I.NUM2);
  END LOOP;
END;
/

------解决方案--------------------
探讨
交换这两行顺序:

dbms_output.put_line('n1=' || n1 || ',n2=' || n2);
exit when v_cur%notfound;
改为:
exit when v_cur%notfound;
dbms_output.put_line('n1=' || n1 || ',n2=' || n2);。。。