17

I'm trying to create a trigger for my table which automatically adds a published date based on when a certain flag is set to 'Y'

I don't have much experience with creating triggers but so far this is what i've got

  create or replace
  TRIGGER ADD_CREATE_DT 
  after UPDATE of approved ON articles 
  for each row
  BEGIN
  :new.create_dt := sysdate where approved = 'Y';
  END;

I get this error when updating the column

trigger 'USER.ADD_CREATE_DT' is invalid and failed re-validation

Any ideas?

Thanks

3 Answers 3

35

Use the WHEN clause:

create or replace
  TRIGGER ADD_CREATE_DT 
  after UPDATE of approved ON articles 
  for each row
  when (new.approved = 'Y')
  BEGIN
  :new.create_dt := sysdate;
  END;

Or use IF:

create or replace
  TRIGGER ADD_CREATE_DT 
  after UPDATE of approved ON articles 
  for each row
  BEGIN
  if :new.approved = 'Y' then
   :new.create_dt := sysdate;
  end if;
  END;

In this case, WHEN is more appropriate and efficient.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - couldn't get the 'WHEN' to work but the 'IF' works perfectly
3
create or replace
  TRIGGER ADD_CREATE_DT 
  after UPDATE of approved ON articles 
  for each row
  BEGIN
    IF :NEW.approved = 'Y' THEN
      :new.create_dt := sysdate;
    END IF;
  END;

Comments

2

I don't know What version of Oracle do you use? In Oracle 10g I got the following error:

ORA-04084: cannot change NEW values for this trigger type
04084. 00000 -  "cannot change NEW values for this trigger type"
*Cause:    New trigger variables can only be changed in before row
           insert or update triggers.
*Action:   Change the trigger type or remove the variable reference.

It does not allow to change the field on AFTER triggers.

1 Comment

A BEFORE trigger definitely seems more appropriate in this case (where the column being updated belongs to the same table that the trigger is on).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.