0

i use oracle demo schema scott to do some plsql test ( the data in that schema are never changed ). i wrote the following program to get the employee number of each department. the problem is, there is just 4 departments but my program output 5 row. i can't find out the reason, anyone can help? great thanks.

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;

2 Answers 2

4

If you output the deptno in the dbms_output you'll see the reason.

You need to switch these two lines:

fetch departments into a_department;
exit when departments%notfound;

%NOTFOUND is meaningless before the initial FETCH; your code was counting the emps in the last dept twice.

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.