为什么我的pl / sql代码显示输出两次?

时间:2016-04-13 04:37:16

标签: oracle plsql

我有两个员工和员工表

雇员

 EMPID FIRSTNAME  LASTNAME       SALARY DEPARTMENT CREDENTIALS
     1 ANITHA     SHARMA          30000 ASSURANCE
     2 EZIO       AUDITORE        50000 ASSURANCE
     3 CONNOR     KENWAY          20000 SUPPORT
     4 SAMANTHA   JO              25000 ASSURANCE
     5 EDWARD     MILES           52000 ITIS

员工

EMP_ID EMP_NAME                EMP_AGE EMP_SALARY     BATHCH
     1 charan                       20      30000
     0                               0          0
     1 goku                         32       1223
     2 gokul                        24     100000

当我尝试编写一个pl / sql代码来打印上面两个表中的emp_name,firstname,salary时,它会打印两次记录.pl / sql代码是

    declare
cursor c1 is select * from employee,employees where employee.salary=employees.emp_salary;
c2 c1%rowtype;
begin
open c1;
loop
fetch c1 into c2;
dbms_output.put_line(c2.firstname||' '||c2.emp_name||' '||c2.salary);
exit when c1%notfound;
end loop;
end;
/

我的输出为

ANITHA charan 30000
ANITHA charan 30000

2 个答案:

答案 0 :(得分:1)

而不是这个,

    declare
cursor c1 is select * from employee,employees where employee.salary=employees.emp_salary;
c2 c1%rowtype;
begin
open c1;
loop
fetch c1 into c2;
dbms_output.put_line(c2.firstname||' '||c2.emp_name||' '||c2.salary);
exit when c1%notfound;
end loop;
end;
/

使用此,

    declare
cursor c1 is select * from employee,employees where employee.salary=employees.emp_salary;
c2 c1%rowtype;
begin
open c1;
loop
fetch c1 into c2; 
exit when c1%notfound;
dbms_output.put_line(c2.firstname||' '||c2.emp_name||' '||c2.salary);
end loop;
end;
/

答案 1 :(得分:0)

exit when之后移动fetch子句。在您的情况下,dbms_output.put_line将被执行两次。对于第二次迭代,即使c2条件为真,not found仍将保留先前的值。

除非您有要求不这样做,否则应始终在exit when之后使用fetch

declare
cursor c1 is select * from employee,employees where employee.salary=employees.emp_salary;
c2 c1%rowtype;
begin
open c1;
loop
fetch c1 into c2; 
exit when c1%notfound;
dbms_output.put_line(c2.firstname||' '||c2.emp_name||' '||c2.salary);
end loop;
end;
/