我正在努力让一名没有经理的员工在我的桌子上展示,但当我知道这样的员工存在于数据库中时,所有我得到的都是“没有找到数据”。
这是我的代码:
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;
感谢您的帮助
答案 0 :(得分: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
答案 1 :(得分:6)
一般情况下,不要先检查记录是否存在,而只是查询。如果在那一刻记录不存在则捕获异常。
begin
select...
exception
when no_data_found then
xyz is not in the table
end;
这样更好,因为您只查询一次。此外,至少在理论上,记录可能会在您的支票和第二个查询之间被删除。所以你仍然需要你的异常处理程序。