2009-07-23 120 views
0

我使用oracle演示模式scott做一些plsql測試(該模式中的數據從不改變)。我編寫了以下程序以獲取每個部門的員工編號。問題是,只有4個部門,但我的程序輸出5行。我找不到原因,任何人都可以幫忙?萬分感謝。plsql光標迭代問題

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; 

回答

3

如果你在dbms_output中輸出deptno,你會看到原因。

需要將以下兩行切換:

fetch departments into a_department; 
exit when departments%notfound; 

%NOTFOUND是無意義的之前的初始FETCH;你的代碼在最後一個部門中統計了兩次。

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;