简体   繁体   English

我正在学习如何制作 PL/SQL 触发器。 这就是我编码的,但我得到了大量的错误

[英]im learning how to make PL/SQL trigger. and this is what i coded but i get tons of errors

this is the description my instructor gave me这是我的导师给我的描述

Create a trigger for the “Worker” table that would fire for INSERT or UPDATE or DELETE operations performed on the “Worker” table.为“Worker”表创建一个触发器,该触发器将触发在“Worker”表上执行的 INSERT 或 UPDATE 或 DELETE 操作。 This trigger will display the salary difference between the old values and new values.此触发器将显示旧值和新值之间的工资差异。 Write a bloc PL/SQL to test the execution of the trigger in response to some database manipulation (DML) statement (DELETE, INSERT, or UPDATE).编写一个块 PL/SQL 来测试触发器的执行,以响应某些数据库操作 (DML) 语句(DELETE、INSERT 或 UPDATE)。

and this is the code:这是代码:

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('diffrence between salary is ' || sal_diff);
end;

You mentioned "tons of errors", but - really - there are only two:您提到了“大量错误”,但是-实际上-只有两个:

  • one that prevents trigger to compile (missing semi-colon after DBMS_OUTPUT.PUT_LINE calls)防止触发器编译的一种(在DBMS_OUTPUT.PUT_LINE调用后缺少分号)
  • another that will prevent trigger to fire when you delete rows (because - in that case - there's no :new value for any column) so - remove the when clause另一个将阻止触发器在您删除行时触发(因为 - 在这种情况下 - 任何列都没有:new值)所以 - 删除when子句

So: sample table:所以:样本表:

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

Table created.

Trigger:扳机:

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 ('diffrence between salary is ' || sal_diff);
 12  END;
 13  /

Trigger created.

Testing:测试:

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

1 row updated.

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

1 row deleted.

SQL>

(when deleting, there's no "difference" because worker doesn't exist any more. If you'd want to see the difference anyway, use NVL function) (删除时,没有“差异”,因为工人不再存在。如果您想看到差异,请使用NVL功能)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM