Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle Trigger not working

I need to develop a trigger which triggers when the value for a field is not 'Y' or 'N'. My code is below which is not working

CREATE OR REPLACE TRIGGER ONLY_Y_N
BEFORE INSERT OR UPDATE OF flag
ON checktable
FOR EACH ROW
BEGIN
IF :new.flag <>'Y' OR  :new.flag <>'N' THEN
RAISE_APPLICATION_ERROR(-20100, 'Please insert Y  or N ');
END IF;
END ONLY_Y_N;

Please help

like image 203
HungryProgrammer Avatar asked Aug 29 '26 01:08

HungryProgrammer


2 Answers

As David Aldridge says, you want a check constraint not a trigger. However, the reason your trigger doesn't work is this condition:

IF :new.flag <>'Y' OR  :new.flag <>'N' THEN

Since 'Y' <> 'N' and 'N' <> 'Y' this will never be true! You need:

IF :new.flag <>'Y' AND  :new.flag <>'N' THEN

or more succinctly:

IF :new.flag not in ('Y', 'N') THEN

So the check constraint solution would be:

alter table checktable add constraint only_y_n check (flag in ('Y', 'N'));
like image 175
Tony Andrews Avatar answered Aug 30 '26 18:08

Tony Andrews


The appropriate method for this would be a check constraint, not a trigger.

Maybe a NOT NULL constraint as well

like image 36
David Aldridge Avatar answered Aug 30 '26 16:08

David Aldridge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!