First of all I'd suggest at least two changes to salhistory
table:
- Define
saldif
as a calculated column - Adding a column to store a datetime when the change occurred, otherwise you won't be able to tell one change from the other.
That being said the table schema for salhistory
may look something like
CREATE TABLE salhistory
(
empno NUMBER NOT NULL,
ename VARCHAR2(32) NOT NULL,
oldsal NUMBER(10,2) NOT NULL,
newsal NUMBER(10,2) NOT NULL,
saldif NUMBER(10,2) AS (newsal - oldsal),
changed DATE NOT NULL,
PRIMARY KEY (empno, changed)
);
Now the trigger
CREATE OR REPLACE TRIGGER tg_salary_history
AFTER UPDATE ON emp
FOR EACH ROW
WHEN (NEW.sal <> OLD.sal) -- log a salary change only if the salary has been actually changed
BEGIN
INSERT INTO salhistory (empno, ename, oldsal, newsal, changed) VALUES
(:OLD.eno, :OLD.ename, :OLD.sal, :NEW.sal, SYSDATE());
END;
/
Here is SQLFiddle demo