【问题标题】:why is my pl/sql code displays output twice?为什么我的 pl/sql 代码显示输出两次?
【发布时间】:2021-09-20 15:38:06
【问题描述】:

我有两张表employee和employees

员工

 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

【问题讨论】:

  • 您的循环退出条件在您的打印语句之后。切换语句,只打印一行。如果将推理留给 OP 作为练习。
  • @user272735 谢谢,它成功了。你能解释一下为什么它会更清楚地打印两次吗?
  • 当 print 语句在循环内时,它将再打印一次。如果查询结果在 1 条语句中,则迭代将尝试第二次执行,如果失败则退出。但是在您退出之前的情况下,它会打印结果。
  • 感谢@NiravMadariya 的解释

标签: oracle plsql


【解决方案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;
/

【讨论】:

  • 它没有用,我仍然得到了两次输出。
  • @RagavCharan 更新了答案。
  • 感谢@NiravMadariya 的回答
【解决方案2】:

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

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

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;
/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    相关资源
    最近更新 更多