Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

triggers to enforce referential integrity

652479Feb 24 2009 — edited Feb 25 2009
I am having trouble setting up a trigger to enable me to enforce referential integrity. I am choosing a trigger as I do not believe it is possible to set it up using constraints.

My parent table (HAB)is of the following structure:

H_ID NUMBER PK
H_CODE VARCHAR2
H_DESCRIPTION

The child table (ATT) is as follows

so_id NUMBER PK
COL_NAME VARCHAR2 PK
VALUE VARCHAR

The table ATT contains in some records information that refers to the HAB table, in these instances col_name = 'HAB' (it can also contain many other value that do not refer to the HAB table)
When the COL_NAME = 'HAB' I want to check that the VALUE column contains a value that is present in HAB.H_ID.

Is it possible to do this with a trigger, I can not figure out how to add a where clause so I only apply the trigger when the col_name column = 'HAB'.

Below is my code so far:

CREATE OR REPLACE TRIGGER TRG_BRYO_ATT_HAB
BEFORE INSERT OR UPDATE
OF VALUE
ON SO_BRY_ATT
REFERENCING NEW AS New OLD AS Old
FOR EACH ROW
WHEN
(NEW.VALUE IS NOT NULL)

DECLARE
Dummy INTEGER; -- used for cursor fetch below
Invalid_habitat EXCEPTION;
Valid_habitat EXCEPTION;
Mutating_table EXCEPTION;
PRAGMA EXCEPTION_INIT (Mutating_table, -4091);

CURSOR Dummy_cursor (hc NUMBER) IS
SELECT h_id FROM hab
WHERE h_id = hc
FOR UPDATE OF h_id;


BEGIN

OPEN Dummy_cursor (:New.value);
FETCH Dummy_cursor INTO Dummy;


IF Dummy_cursor%NOTFOUND THEN
RAISE Invalid_hab;
ELSE
RAISE valid_hab;
END IF;
CLOSE Dummy_cursor;
EXCEPTION
WHEN Invalid_hab THEN
CLOSE Dummy_cursor;
Raise_application_error(-20000, 'Invalid hab'
|| ' code' || TO_CHAR(:New.value));
WHEN Valid_hab THEN
CLOSE Dummy_cursor;
WHEN Mutating_table THEN
NULL;

END TRG_BRYO_ATT_HAB;



/

Any guidance on how to do this, or suggestions of better ways to enforce this would be much appreciated.

Thanks

Stef
This post has been answered by Peter Gjelstrup on Feb 25 2009
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 25 2009
Added on Feb 24 2009
8 comments
275 views