[英]Compilation error on oracle trigger
我有一個具有雇員的表(oracle SQL),其中每個雇員都有一個經理(表示為另一個雇員的fk)。 我想創建一個觸發器,當刪除雇員時,在其經理字段中具有其鍵的所有雇員都將其經理更改為null(或-1,或某些保留值)。 我在弄清楚當前代碼出了什么問題時遇到了一些麻煩:
編輯:我修復了我的大部分代碼,並且我正以錯誤的方式進行操作。 我使用了建議的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';
您不想在這里使用觸發器。 使用外鍵的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.