将任何员工删除到员工表中时如何构建触发器以复制行
Posted
技术标签:
【中文标题】将任何员工删除到员工表中时如何构建触发器以复制行【英文标题】:How to build a trigger to copy row when delete any employee into the employees table 【发布时间】:2021-06-07 13:40:37 【问题描述】:我想构建一个触发器,当记录从员工表中删除时,复制记录并将其放入新表中。
我尝试过这样做,但它不起作用
create or replace trigger log_delete_employee
after delete on employees
for each row
declare
begin
insert into deleted_employees value('delete',employee_id, first_name, salary);
end;
【问题讨论】:
but it is doesn't work
对我们没有任何意义
您的触发代码使用了无效的语法。解决方案在the PL/SQL documentation。 Oracle 文档是在线的、全面的和免费的。我建议您将其加入书签以供将来参考。
【参考方案1】:
我认为主要的问题是您没有使用 :old
伪记录引用旧值。
除此之外,我建议你这样做
修改表格并添加更多列 - 谁删除了该记录以及何时删除 始终指定您编写的语句中涉及的所有列;是的,这需要更多的输入,但更容易理解和调试(如有必要)这是一个示例:包含已删除行的表:
SQL> create table deleted_employees
2 (action varchar2(10),
3 datum date,
4 who varchar2(20),
5 employee_id number,
6 first_name varchar2(10),
7 salary number
8 );
Table created.
SQL>
触发器:
SQL> create or replace trigger log_delete_employee
2 after delete on employees
3 for each row
4 begin
5 insert into deleted_employees
6 (action,
7 datum,
8 who,
9 employee_id,
10 first_name,
11 salary
12 )
13 values
14 ('delete',
15 sysdate,
16 user,
17 :old.employee_id,
18 :old.first_name,
19 :old.salary
20 );
21 end;
22 /
Trigger created.
SQL>
测试:当前表格内容:
SQL> select * from employees;
EMPLOYEE_ID FIRST_NAME SALARY
----------- ---------- ----------
7369 SMITH 800
7499 ALLEN 1600
7521 WARD 1250
7566 JONES 2975
7654 MARTIN 1250
让我们删除其中一个:
SQL> delete from employees where first_name = 'SMITH';
1 row deleted.
结果:
SQL> select * from deleted_employees;
ACTION DATUM WHO EMPLOYEE_ID FIRST_NAME SALARY
---------- ------------------- ---------- ----------- ---------- ----------
delete 07.06.2021 21:46:39 SCOTT 7369 SMITH 800
SQL> select * from employees;
EMPLOYEE_ID FIRST_NAME SALARY
----------- ---------- ----------
7499 ALLEN 1600
7521 WARD 1250
7566 JONES 2975
7654 MARTIN 1250
SQL>
【讨论】:
【参考方案2】:在插入新表时,您需要使用 :old
psuedocolumn 关键字从行中引用被删除的值(即旧值)。
create or replace trigger log_delete_employee
after delete on employees
for each row
declare
begin
insert into deleted_employees value('delete',:old.employee_id, :old.first_name, :old.salary);
end;
【讨论】:
以上是关于将任何员工删除到员工表中时如何构建触发器以复制行的主要内容,如果未能解决你的问题,请参考以下文章