plsql游标迭代问题

plsql游标迭代问题,plsql,cursor,iteration,Plsql,Cursor,Iteration,我使用OracleDemoSchemascott进行一些plsql测试(该模式中的数据从未更改)。我编写了以下程序来获取每个部门的员工编号。问题是,只有4个部门,但我的程序输出了5行。我找不出原因,有人能帮忙吗?非常感谢 declare cursor employees(department_id number) is select count(*) howmany from scott.emp where deptno=department_id; e

我使用OracleDemoSchemascott进行一些plsql测试(该模式中的数据从未更改)。我编写了以下程序来获取每个部门的员工编号。问题是,只有4个部门,但我的程序输出了5行。我找不出原因,有人能帮忙吗?非常感谢

declare
    cursor employees(department_id number) is
    select count(*) howmany
    from scott.emp
    where deptno=department_id;

    employees_per_dept employees%rowtype;


    cursor departments is
    select *
    from scott.dept;

    a_department departments%rowtype;

begin
    dbms_output.put_line('-----------------------------------');
    open departments;
    loop
        exit when departments%notfound;

        fetch departments into a_department;

        open employees(a_department.deptno);
        fetch employees into employees_per_dept;
        dbms_output.put_line(employees_per_dept.howmany);
        close employees;


    end loop;
    close departments;
    dbms_output.put_line('-----------------------------------');
end;

如果在dbms_输出中输出deptno,您将看到原因

您需要切换这两条线路:

fetch departments into a_department;
exit when departments%notfound;

%NOTFOUND在初始提取之前没有意义;您的代码在计算上一个部门的EMP两次。

如果在dbms\u输出中输出deptno,您将看到原因

declare

cursor cl(ccode varchar2) is

Select * from employees where department_id=ccode;

z cl%rowtype;

cnt number:=0;

begin

    Open cl('90');

    fetch cl into Z;

    while (cl%found) loop 

    dbms_output.put_line ( 'nsme is  '  || z.last_name);

        fetch cl into Z;

        cnt := cnt +1;

        end  loop;

         dbms_output.put_line (cnt);

    close cl;

   end;
您需要切换这两条线路:

fetch departments into a_department;
exit when departments%notfound;
%NOTFOUND在初始提取之前没有意义;你的密码是两次计算最后一个部门的EMP

declare

cursor cl(ccode varchar2) is

Select * from employees where department_id=ccode;

z cl%rowtype;

cnt number:=0;

begin

    Open cl('90');

    fetch cl into Z;

    while (cl%found) loop 

    dbms_output.put_line ( 'nsme is  '  || z.last_name);

        fetch cl into Z;

        cnt := cnt +1;

        end  loop;

         dbms_output.put_line (cnt);

    close cl;

   end;