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. 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).
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:
DBMS_OUTPUT.PUT_LINE
calls):new
value for any column) so - remove the when
clauseSo: 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.