0

我使用 oracle 演示模式scott进行一些 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;
4

2 回答 2

4

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

您需要切换这两行:

fetch departments into a_department;
exit when departments%notfound;

%NOTFOUND 在初始 FETCH 之前是没有意义的;你的代码计算了最后一个部门的雇员两次。

于 2009-07-24T12:12:44.737 回答
0
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;
于 2013-11-27T06:34:49.653 回答