使用触发器实现外键检查约束

时间:2014-03-02 15:44:58

标签: oracle plsql triggers foreign-keys

我正在尝试将此约束实现到我的数据库中: (在表Race中) CONSTRAINT(日期< = Meeting.EndDate)

基本上,Race Table中的列需要小于Meeting表中的EndDate列。

非常确定我需要使用触发器来实现外键,但是,我不确定如何实现外键。到目前为止,我只有:

CREATE OR REPLACE TRIGGER RaceDateCheck
AFTER UPDATE OF Race ON StartDateCheck
BEGIN
 INSERT INTO Race
    (MeetingEndDate)
 SELECT EndDate FROM Meeting
END;

谢谢,

1 个答案:

答案 0 :(得分:1)

大概比赛日期必须在会议开始和结束日期之间,所以你可以同时检查两个;并且也可能想要检查这个新记录,而不仅仅是更新。所以你可以使用类似的东西:

CREATE OR REPLACE TRIGGER RaceDateCheck
BEFORE INSERT OR UPDATE ON Race
FOR EACH ROW
DECLARE
  meetingStart Meeting.MeetingStartDate%TYPE;
  meetingEnd Meeting.MeetingEndDate%TYPE;
BEGIN
  SELECT StartDate, EndDate
  INTO meetingStart, meetingEnd
  FROM Meeting
  WHERE MeetingID = :NEW.MeetingID;

  IF :NEW.RaceDate < meetingStart
    OR :NEW.RaceDate > meetingEnd THEN
      RAISE_APPLICATION_ERROR(-20001, 'Invalid race date');
  END IF;
END;

仅限结束日期:

CREATE OR REPLACE TRIGGER RaceDateCheck
BEFORE INSERT OR UPDATE ON Race
FOR EACH ROW
DECLARE
  meetingEnd Meeting.MeetingEndDate%TYPE;
BEGIN
  SELECT EndDate
  INTO meetingEnd
  FROM Meeting
  WHERE MeetingID = :NEW.MeetingID;

  IF :NEW.RaceDate > meetingEnd THEN
    RAISE_APPLICATION_ERROR(-20001, 'Invalid race date');
  END IF;
END;