fetch cemp into pename,psal;
EXIT when cemp%notfound;
与
EXIT when cemp%notfound;
fetch cemp into pename,psal;
得出的结果不一样,这是为什么?
第一种方式结果如下:
... MILLER的薪水是:1300
第二种结果如下:
... MILLER的薪水是:
1300 MILLER的薪水是:
1300
第二种最后一条记录重复出现两次是何原因?
fetch是用来提取游标数据的,你这样写,会多一次提取数据的机会
set serveroutput on
declare
cursor s is select ename from emp;
pename emp.ename%type;
begin
open s;
loop
exit when s%notfound;
dbms_output.put_line('before:'||pename);
fetch s into pename;
dbms_output.put_line('after:'||pename);
end loop;
close s;
end;
/
输出结果:
before:
after:SMITH
before:SMITH
after:ALLEN
before:ALLEN
after:WARD
before:WARD
after:JONES
before:JONES
after:MARTIN
before:MARTIN
after:BLAKE
before:BLAKE
after:CLARK
before:CLARK
after:KING
before:KING
after:TURNER
before:TURNER
after:JAMES
before:JAMES
after:FORD
before:FORD
after:MILLER
before:MILLER
after:MILLER
第一次判断没跳转,只是证明表里有记录,在取值之前一直是上一条数据的记录。
set serveroutput on
declare
cursor s is select ename from emp;
pename emp.ename%type;
num number:= 16;
begin
open s;
loop
exit when num<0;
dbms_output.put_line('before:'||pename);
fetch s into pename;
dbms_output.put_line('after:'||pename);
num := num -1;
end loop;
close s;
end;
/
输出结果:
before:
after:SMITH
before:SMITH
after:ALLEN
before:ALLEN
after:WARD
before:WARD
after:JONES
before:JONES
after:MARTIN
before:MARTIN
after:BLAKE
before:BLAKE
after:CLARK
before:CLARK
after:KING
before:KING
after:TURNER
before:TURNER
after:JAMES
before:JAMES
after:FORD
before:FORD
after:MILLER
before:MILLER
after:MILLER
before:MILLER
after:MILLER
before:MILLER
after:MILLER
before:MILLER
after:MILLER
before:MILLER
after:MILLER
证明fetch跳到最后一条记录以后就不会再报NULL值了,而是一直保存最有一个值。
综上所述:循环多执行了一遍,最后一个值被多打印了一次!希望对你有帮助!
可能是光标取值之后,何时会跳转到下一条记录,跟这个有关,就是在最后一次判断的时候光标还没有跳到下一条记录。