0

I am trying to create a trigger to calculate a derived attribute on each insert command. However I am getting compilation errors, I dont know where is the problem.

CREATE OR REPLACE TRIGGER NewTrigger 
BEFORE INSERT 
ON Dates FOR EACH ROW 
 BEGIN 
   SET :NEW.difference := :NEW.date1 - :NEW.date2; 
 END;

Show errors shows me this information:

LINE/COL ERROR
-------- -----------------------------------------------------------------
1/7  PL/SQL: SQL Statement ignored
1/11     PL/SQL: ORA-00922: missing or invalid option
5
  • What's the date type of dates.difference? Commented Dec 18, 2012 at 14:12
  • There must be something you are not telling us, because that should work. Commented Dec 18, 2012 at 14:18
  • the type of difference is number Commented Dec 18, 2012 at 14:42
  • Appearently "SET" keyword is not needed. Commented Dec 18, 2012 at 15:10
  • FYI - SET is a SQL*plus command, not PL/SQL. Commented Dec 19, 2012 at 3:40

2 Answers 2

2

It's not the trigger, it's the data type. If you substract a date from another date, the result is an interval, not another date:

CREATE TABLE dates (date1 DATE, date2 DATE, datediff DATE, numdiff NUMBER);
INSERT INTO dates (date1, date2) VALUES (sysdate, sysdate-1);

UPDATE dates SET numdiff = date1 - date2;
1 rows updated

UPDATE dates SET datediff = date1 - date2;
SQL Error: ORA-00932: inconsistent datatypes: expected DATE got DATE JULIAN

So, if the trigger stores the interval in a number, it compiles:

CREATE OR REPLACE TRIGGER newtriggernum
  BEFORE INSERT ON dates FOR EACH ROW
BEGIN
  :new.numdiff := :new.date1 - :new.date2;
END;
/
TRIGGER NEWTRIGGERNUM compiled

and if it stores the interval in a date, it doesn't:

CREATE OR REPLACE TRIGGER newtriggerdate
  BEFORE INSERT ON dates FOR EACH ROW
BEGIN
  :new.datediff := :new.date1 - :new.date2;
END;
/
Error(2,11): PL/SQL: ORA-00922: missing or invalid option
Sign up to request clarification or add additional context in comments.

Comments

0
CREATE OR REPLACE TRIGGER NewTrigger
BEFORE INSERT ON Dates FOR EACH ROW
BEGIN 
    :NEW.difference := :NEW.date1 - :NEW.date2;
End;
/

1 Comment

No, that doesn't compile either with the same error message :-(

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.