creating a trigger in oracle that uses data from another table

扶醉桌前 提交于 2020-01-15 09:22:04

问题


I am trying to create a trigger in a table called race that enforces a constraint which is "STARTDATE<=MEETING.ENDDATE"

in other words startdate from the race table must be less than or equals to to the enddate of the meetings table (THE STARTDATE CANNOT BE RUN AFTER THIS DATE!)

I would like the trigger to fire when adding a record to the race table and the startdate entered is wrong (startdate is after the enddate of the meetings table)

I have created this so far but I don't know if I'm right or how I finish it!

CREATE OR REPLACE TRIGGER race_date_trg    
BEFORE INSERT OR UPDATE
  ON RACE
  FOR EACH ROW
  WHEN (NEW.RACEID)
   DECLARE STARTDATE DATE;
  BEGIN
    SELECT * FROM meeting INTO VARIABLE
    IF STARTDATE <= ENDDATE THEN
      INSERT INTO RACE (STARTDATE) VALUES (:n.startdate);
    else
  end (race_date_trg);

Thank-you for your help!


回答1:


You have a lot of mistakes in your trigger.

  1. You don't have to declare STARTDATE variable, you should use :new.STARTDATE
  2. Expression WHEN (:new.RACEID) is wrong
  3. You must declare VARIABLE before selecting to it.
  4. Your trigger shouldn't insert into Race. You could raise an error if start date is incorrect.

The trigger could look like this:

CREATE OR REPLACE TRIGGER race_date_trg    
BEFORE INSERT OR UPDATE
  ON RACE
  FOR EACH ROW
  DECLARE
    MEETING_ENDDATE DATE;
  BEGIN
    SELECT ENDDATE INTO MEETING_ENDDATE FROM meeting;
    IF :NEW.STARTDATE > MEETING_ENDDATE THEN
      RAISE_APPLICATION_ERROR(-20000, 'Wrong start date!');
    END IF:
  end race_date_trg;


来源:https://stackoverflow.com/questions/22013628/creating-a-trigger-in-oracle-that-uses-data-from-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!