Oracle触发器检查一个表中的课程持续时间,如果课程是特定日期,则阻止更新

时间:2013-03-26 17:09:22

标签: oracle plsql triggers

如果我问的问题已在其他地方得到解答,请提出道歉,但我找不到合适的答案。我知道如何基于一个表创建简单的触发器,但是我试图在两个表中实现链接更新。以下是场景:在课程表中是持续时间列,在产品表中有一个start_date列。产品是提供课程的实例,两个表(课程和产品)通过course_id链接。如果对应的课程有5天的持续时间,我需要创建一个触发器来阻止产品表在1月份开始日期。我试图创建这个触发器并且可以发布我的努力,但我绝对不在乎我确定。

CREATE OR REPLACE TRIGGER check_duration
  BEFORE UPDATE on offering
  FOR EACH ROW
BEGIN
  SELECT c.duration
  INTO duration
  FROM course c
  WHERE c.duration = 5
IF(:new.start_date BETWEEN to_date('01/01/2013', 'DD/MM/YYY') AND to_date('31/01/2013', 'DD/MM/YYY')
  THEN RAISE_APPLICATION_ERROR(20100, 'Cannot run particular course during this month')
END IF;
END;

课程表:

Course_id(pk) | Title | Duration | Cost

提供表格:

offering_id(pk) | start_date | location | instructor | course_id(fk)

另外还有另外两张表Attendance和Student我认为我不需要为这个问题发布这些表的构造

1 个答案:

答案 0 :(得分:0)

如果有关于表格的任何新信息,您可能需要调整此项,但这里是基于您的评论的初始尝试,offering表中有一个courseid列:

CREATE OR REPLACE TRIGGER check_duration
  BEFORE UPDATE on offering
  FOR EACH ROW
DECLARE
  isFound NUMBER;
BEGIN
  -- Just want to know if there's a duration 5 record for the course...
  SELECT 1 INTO isFound FROM DUAL WHERE EXISTS (
    SELECT * FROM course c
    WHERE c.course_id = :NEW.course_id AND c.duration = 5);
  -- Fallthrough to here means a course was found with duration 5. Is
  -- it scheduled for January (month #1) of any year?
  IF EXTRACT(MONTH FROM :NEW.start_date) = 1 THEN
    THEN RAISE_APPLICATION_ERROR(20100, 'Cannot run particular course during this month');
  END IF;
EXCEPTION
  -- If the query didn't find a course with duration 5 it throws
  -- a NO_DATA_FOUND exception. Ignore the exception because not
  -- finding a course means it's OK to add the row.
  WHEN NO_DATA_FOUND THEN
    NULL;
END;