oracle 我正在学习如何使PL/SQL触发器,这是我编写的代码,但我得到了大量的错误

eh57zj3b  于 2023-04-20  发布在  Oracle
关注(0)|答案(1)|浏览(168)

这是我的导师给我的描述
为“Worker”表创建一个触发器,该触发器将在对“Worker”表执行INSERT、UPDATE或DELETE操作时触发。此触发器将显示旧值和新值之间的工资差异。编写一个块PL/SQL以测试触发器的执行情况,以响应某些数据库操作(DML)语句(DELETE、INSERT或UPDATE)。
这是代码:

create or replace trigger salary_diff
before delete or insert or update on Worker
for each row 
when (new.Worker_id > 0 )

declare
sal_diff number;
begin
sal_diff := :new.salary - :old.salary;
dbms_output.put_line('new salary ' ||  :new.salar)
dbms_output.put_line('old salary ' ||  :old.salary)
dbms_output.put_line('difference between salary is ' || sal_diff);
end;
bq8i3lrv

bq8i3lrv1#

你提到了“大量的错误”,但实际上只有两个:

  • 一个防止触发器编译的函数(DBMS_OUTPUT.PUT_LINE调用后缺少分号)
  • 另一个是防止在删除行时触发器(因为在这种情况下,任何列都没有:new值),因此删除when子句

So:sample table:

SQL> CREATE TABLE worker
  2  AS
  3     SELECT 1 worker_id, 100 salary FROM DUAL;

Table created.

触发器:

SQL> CREATE OR REPLACE TRIGGER salary_diff
  2     BEFORE DELETE OR INSERT OR UPDATE
  3     ON Worker
  4     FOR EACH ROW
  5  DECLARE
  6     sal_diff  NUMBER;
  7  BEGIN
  8     sal_diff := :new.salary - :old.salary;
  9     DBMS_OUTPUT.put_line ('new salary ' || :new.salary);
 10     DBMS_OUTPUT.put_line ('old salary ' || :old.salary);
 11     DBMS_OUTPUT.put_line ('difference between salary is ' || sal_diff);
 12  END;
 13  /

Trigger created.

测试:

SQL> SET SERVEROUTPUT ON
SQL> UPDATE worker
  2     SET salary = 50
  3   WHERE worker_id = 1;
new salary 50
old salary 100
difference between salary is -50

1 row updated.

SQL> DELETE FROM worker
  2    WHERE worker_id = 1;
new salary
old salary 50
difference between salary is

1 row deleted.

SQL>

(when删除,没有“区别”,因为工人不再存在。如果你想看到的差异无论如何,使用NVL函数)

相关问题