0

我编写了这个触发器,它监视一个名为 employees 的表,当从该表中删除一个员工时,触发器应该触发,并复制我们要从表中删除的员工 employees 并放入另一个名为 deleted_employees 的表中,但是当我把以下sql 语句 delete from employees where employee_id = 100 SQL 错误说:

Error starting at line 17 in command:
delete from employees where employee_id = 100
Error report:
SQL Error: ORA-02292: integrity constraint (HR.DEPT_MGR_FK) violated - child
                      record found
02292. 00000 - "integrity constraint (%s.%s) violated - child record found"
*Cause:    attempted to delete a parent key value that had a foreign
           dependency.
*Action:   delete dependencies first then parent or disable constraint.

CREATE OR REPLACE TRIGGER EMPLOYEE_DELETED 
  BEFORE DELETE ON EMPLOYEES 
DECLARE
  CURSOR CUR_EMP IS
    SELECT  EMPLOYEE_ID , FIRST_NAME , LAST_NAME , EMAIL , 
            PHONE_NUMBER , HIRE_DATE , JOB_ID , SALARY ,
            COMMISSION_PCT ,  MANAGER_ID , DEPARTMENT_ID
      FROM EMPLOYEES;
  EMP_REC CUR_EMP%ROWTYPE;
BEGIN
  OPEN CUR_EMP;

  while(CUR_EMP%FOUND) LOOP
    FETCH CUR_EMP INTO EMP_REC;
    INSERT  INTO deleted_employees
      (EMPLOYEE_ID , FIRST_NAME , LAST_NAME ,
       EMAIL ,
       PHONE_NUMBER , HIRE_DATE ,job_id , salary ,
       COMMISSION_PCT ,  MANAGER_ID , DEPARTMENT_ID)
    VALUES
      (EMP_REC.EMPLOYEE_ID ,EMP_REC.FIRST_NAME ,EMP_REC.LAST_NAME ,
       EMP_REC.EMAIL , EMP_REC.PHONE_NUMBER , EMP_REC.HIRE_DATE ,
       EMP_REC.JOB_ID , EMP_REC.SALARY , EMP_REC.COMMISSION_PCT ,
       EMP_REC.MANAGER_ID , EMP_REC.DEPARTMENT_ID);
  END LOOP;

  CLOSE CUR_EMP;
END;

我不知道如何测试触发器,有什么想法吗?!

4

1 回答 1

1

我观察到的一件事是,您错误地将 EMPLOYEE 表中的所有记录插入到 DELETED_EMPLOYEES 中。

我认为您想将员工详细信息插入到当前处于删除操作中的 deleted_employee 表中。

在 Oracle 中,您可以使用:OLD关键字来引用当前运行记录。好吧,如果您还想删除相关的智利记录..那么您可以在此触发器本身中进行操作,而不会出现任何问题-

CREATE OR REPLACE TRIGGER EMPLOYEE_DELETED 
BEFORE DELETE ON EMPLOYEES 
FOR EACH ROW
DECLARE
BEGIN
INSERT  INTO deleted_employees
(
 EMPLOYEE_ID , FIRST_NAME , LAST_NAME , EMAIL ,
 PHONE_NUMBER , HIRE_DATE ,job_id , salary ,
 COMMISSION_PCT ,  MANAGER_ID , DEPARTMENT_ID
)
VALUES
(:OLD.EMPLOYEE_ID ,:OLD.FIRST_NAME ,:OLD.LAST_NAME , :OLD.EMAIL ,
 :OLD.PHONE_NUMBER , :OLD.HIRE_DATE , :OLD.JOB_ID , :OLD.SALARY ,
 :OLD.COMMISSION_PCT ,  :OLD.MANAGER_ID , :OLD.DEPARTMENT_ID);

DELETE from DEPARTMENT where EMPLOYEE_ID = :OLD.EMPLOYEE_ID; -- If you are deleting child record then you will not get ORA:02292 error

END;

只需delete根据您的数据库编辑此触发器中的部分。

为此,您需要首先检查键约束DEPT_MGR_FK。我猜想这个键存在于 EMPLOYEE_ID 列的 DEPARTMENT 表中。

所以检查这个键并更改倒数第二行然后编译。

于 2013-05-19T22:20:36.750 回答