2013-10-10 77 views
0

我有一个雇员表(oracle SQL),其中每个雇员都有一个经理(表示为另一个雇员的fk)。我想创建一个触发器,当员工被删除时,所有在他们的经理字段中拥有其关键字的员工都将其管理器更改为空(或-1或一些保留值)。我在计算当前代码有什么问题时遇到了一些问题:oracle触发器上的编译错误

编辑: 我修复了我的大部分代码,并且我以错误的方式解决了这个问题。我使用了建议的ON DELETE选项,现在一切正常。这里是我的代码:

CREATE TABLE EmployeeA 
(
    employeeID integer, 
    firstName varchar (255), 
    lastName varchar (255), 
    phone integer, 
    jobTitle varchar (255), 
    payGrade integer, 
    fk_EmployeeemployeeID integer, 
    PRIMARY KEY(employeeID), 
    FOREIGN KEY(fk_EmployeeemployeeID) REFERENCES EmployeeA (employeeID) ON DELETE SET NULL 
); 
INSERT INTO EMPLOYEEA VALUES (1, null, 'Powell', 0, 'President', 100, 1); 
INSERT INTO EMPLOYEEA VALUES (2, null, 'Hicke', 0, 'Dean (Natural Science)', 100, 1); 
INSERT INTO EMPLOYEEA VALUES (3, null, 'Fenves', 0, 'Dean (Engineering)', 100, 1); 
INSERT INTO EMPLOYEEA VALUES (4, null, 'Porter', 0, 'Chairman (Computer Science)', 100, 2); 
INSERT INTO EMPLOYEEA VALUES (5, null, 'Beckner', 0, 'Chairman (Mathematics)', 100, 2); 
INSERT INTO EMPLOYEEA VALUES (6, null, 'Miranker', 0, 'Professor (Computer Science)', 100, 4); 
INSERT INTO EMPLOYEEA VALUES (7, null, 'Mok', 0, 'Professor (Computer Science)', 100, 4); 
DELETE FROM employeeA WHERE lastName = 'Porter';  
+0

我相信你会得到哪怕它可以被编译另一个错误,甲骨文抱怨说,你不能更新同一表,触发器就可以了。你为什么不更新NEW记录? –

+0

因为我们不应该关心新纪录。新记录是新的经理人行,但我们希望向经理报告的员工将其经理字段设置为空。 – zaloo

+0

这是一个家庭作业,你必须使用触发器?或者你能够使用外键的'on delete'属性吗? –

回答

1

你不想在这里使用触发器。使用外键的on delete属性。在定义外键约束时,可以指定当父行被删除时您希望它将子行设置为NULL

SQL> ed 
Wrote file afiedt.buf 

    1 create table employee2(
    2 employee_id number primary key, 
    3 manager_id number, 
    4 employee_first_name varchar(30), 
    5 constraint fk_manager_emp 
    6  foreign key(manager_id) 
    7  references employee2(employee_id) 
    8  on delete set null 
    9*) 
SQL>/

Table created. 

如果再加上一个老板,经理(谁报告给老板),和雇员(谁报告给经理)

SQL> insert into employee2(employee_id, manager_id, employee_first_name) 
    2 values(1, null, 'Boss'); 

1 row created. 

SQL> ed 
Wrote file afiedt.buf 

    1 insert into employee2(employee_id, manager_id, employee_first_name) 
    2* values(2, 1, 'Emp1') 
SQL>/

1 row created. 

SQL> ed 
Wrote file afiedt.buf 

    1 insert into employee2(employee_id, manager_id, employee_first_name) 
    2* values(3, 2, 'Emp2') 
SQL>/

1 row created. 

那么当我们删除经理,员工的manager_id自动被设置为NULL

SQL> delete from employee2 
    2 where employee_first_name = 'Emp1'; 

1 row deleted. 

SQL> select * 
    2 from employee2 
    3 where employee_first_name = 'Emp2'; 

EMPLOYEE_ID MANAGER_ID EMPLOYEE_FIRST_NAME 
----------- ---------- ------------------------------ 
      3   Emp2