我正在努力做到这一点,以便我创建的数据库可以适应变化。我有一个员工表,其中每一行都有一个员工中另一行的外键(这代表每个员工的经理是谁)。我想要做的是,当我完成交换两名员工职位的交易时,外键在交易后具有正确的值。
例如,如果我们有:
ID | jobTitle | fk
1 superboss 1
2 boss 1
3 lessboss 2
4 notboss 3
我们在单个事务中交换 notboss 和 less boss 的职位和外键,我们希望结果表如下所示:
ID | jobTitle | fk
1 superboss 1
2 lessboss 3
3 boss 1
4 notboss 2
我实现这些更改的方法是创建一个在更新 jobTitle 时触发的触发器。它将查找具有先前外键的所有行并将其更改为具有旧值 jobTitle 的行中的 fk 的值。出于某种原因,我的 CREATE TRIGGER 出现编译错误。我已经在下面发布了我的代码。
CREATE TABLE EmployeeB
(
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 EmployeeB (employeeID)
ON DELETE SET CASCADE
);
CREATE OR REPLACE TRIGGER ManagerTrigger1A
AFTER UPDATE OF jobTitle ON employeeB
REFERENCING OLD AS OldRow NEW AS NewRow
BEGIN
UPDATE employeeB SET FK_EMPLOYEEEMPLOYEEID = (SELECT employeeID FROM employeeB WHERE jobTitle = :OldRow.jobTitle AND rownum <2)
WHERE (SELECT employeeID FROM employeeB WHERE jobTitle = :OldRow.jobTitle) != null;
END;
CREATE OR REPLACE TRIGGER ManagerTrigger1B
AFTER UPDATE OF jobTitle ON employeeB
REFERENCING OLD AS OldRow NEW AS NewRow
BEGIN
DELETE FROM employeeB WHERE (SELECT employeeID FROM employeeB WHERE jobTitle = :OldRow.jobTitle) = null;
END;
我不确定这是否是解决我的问题的最佳方法,因此,如果我以错误的方式解决此问题,或者您有更好的主意,请告诉我。无论哪种方式,我仍然想知道为什么会出现此编译错误。
编辑:忘记了我得到的错误。
Error starting at line 1 in command:
CREATE OR REPLACE TRIGGER ManagerTrigger1A
AFTER UPDATE OF jobTitle ON employeeB
REFERENCING OLD AS OldRow NEW AS NewRow
BEGIN
UPDATE employeeB SET FK_EMPLOYEEEMPLOYEEID = (SELECT employeeID FROM employeeB WHERE jobTitle = :OldRow.jobTitle AND rownum <2)
WHERE (SELECT employeeID FROM employeeB WHERE jobTitle = :OldRow.jobTitle) != null;
END;
Error report:
ORA-04082: NEW or OLD references not allowed in table level triggers
04082. 00000 - "NEW or OLD references not allowed in table level triggers"
*Cause: The trigger is accessing "new" or "old" values in a table trigger.
*Action: Remove any new or old references.
编译错误:
Error(2,1): PL/SQL: SQL Statement ignored
Error(2,97): PL/SQL: ORA-00904: "OLD"."MANAGER"."JOBTITLE": invalid identifier