PL/SQL中找不到数据

Geo*_*Geo 1 sql oracle plsql oracle11g

我想让一个没有经理的员工在我的桌子上展示,但当我知道这样的员工存在于数据库中时,所有我得到的都是"没有找到数据".

这是我的代码:

ACCEPT p_1 PROMPT 'Please Enter Employee ID:'

declare 
  v_eid               employee.employee_id%TYPE := &p_1;
  v_count             NUMBER;
  v_name              employee.employee_name%TYPE;
  v_sal               employee.salary%type;
  v_mname             employee.employee_id%TYPE ;
  v_dptname           department.department_name%type;  
  v_avg               employee.salary%type;

BEGIN 
  SELECT count(*)
  INTO v_count
  FROM employee
  WHERE employee_id = v_eid;

  IF v_count = 0 THEN
      DBMS_OUTPUT.PUT_LINE(v_eid || ' is not in the table.');
  ELSE
      select e1.employee_name, e1.salary, department.department_name,
             nvl(e2.employee_name, 0)
      into v_name, v_sal, v_mname, v_dptname
      from employee e1
      inner join employee e2 on e1.manager_id = e2.employee_id 
      inner join department on e1.department_id = department.department_id
      where e1.employee_id = v_eid;

      select AVG(salary)
      into v_avg
      from employee
      where department_id = (select department_id 
                              from employee 
                              where employee_id=v_eid);
        DBMS_OUTPUT.PUT_LINE('Name:'|| LPAD(v_name,30));
        DBMS_OUTPUT.PUT_LINE('Salary:'|| LPAD(to_char(v_sal,'$9,999.00'),28));
        DBMS_OUTPUT.PUT_LINE('Manager Name:'|| LPAD(v_mname, 19));
        DBMS_OUTPUT.PUT_LINE('Department Name:'|| v_dptname);
        DBMS_OUTPUT.PUT_LINE('Department Average'|| to_char(v_avg,'$9,999.00'));
  END IF;
END;
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助

jos*_*989 7

嗨如果你只是寻找没有经理的员工,你为什么要自我加入.无论如何,如果没有经理,你应该更换

from employee e1 inner join employee e2 on e1.manager_id = e2.employee_id 

by

from employee e1 left outer join employee e2 on e1.manager_id = e2.employee_id 
Run Code Online (Sandbox Code Playgroud)


Ren*_*ene 6

通常,不要先检查是否存在记录,而只是查询.如果在那一刻记录不存在则捕获异常.

begin
   select...

exception
   when no_data_found then
      xyz is not in the table
end;
Run Code Online (Sandbox Code Playgroud)

这样更好,因为您只查询一次.此外,至少在理论上,记录可能会在您的支票和第二个查询之间被删除.所以你仍然需要你的异常处理程序.