I have the following trigger which gets fired when updated becomes Y. I would like to insert the old values only if values do not exist in my_hist table. If the same record exists then it should not insert. For this best way is whether to create a constraint to check uniqueness in my_hist table or check this condition in trigger? If so how could I do this in trigger?
Or is it possible to check the unique constraint of my_hist table in trigger so that it will not insert duplicate records.
CREATE OR REPLACE TRIGGER mytrig
AFTER UPDATE
ON mytab
FOR EACH ROW
WHEN (
new.updated = 'Y'
)
BEGIN
INSERT INTO my_hist
VALUES (
:old.id,
:old.no,
:old.start_date,
:old.end_date,
SYSDATE
);
END mytrig;
/
You can change your
insertto the following in order to check if a duplicate exists already. The select assumes that the primary key ofmy_histisidandstart_date, change thewhere not existsclause to use only the primary key values if they’re different.However, this requires an index scan so it’s not that optimal.
Instead let the exception get raised. It’s explicitly named:
dup_val_on_index. If this does get raised then simply ignore it.