5

我有两张桌子,COURSEOFFERING。他们的专栏是:

COURSE (
   courseId, 
   title, 
   cost, 
   duration
) 

OFFERING (
    offeringID, 
    instructor, 
    startDate, 
    endDate, 
    courseId, 
    locationId
 ). 

我想配置一个触发器,确保COURSE不能在 12 月提供持续时间为 5 天的课程(来自表格的持续时间列)(来自表格的startDateOFFERING)。我想出了以下 SQL 查询:

CREATE OR REPLACE TRIGGER checkDuration
BEFORE INSERT OR UPDATE ON 
  (course c JOIN offering o
   ON   
   c.courseId = o.courseId)
FOR EACH ROW
BEGIN
  IF ((to_char(:new.startDate, 'fmMONTH') = 'DECEMBER') AND duration = 5) 
  THEN
     raise_application_error(-20001, 'Courses of five days duration cannot be run in December');
  END IF;
END;

触发器已创建,但出现错误。

4

2 回答 2

3

这非常有效。

CREATE OR REPLACE TRIGGER checkDuration
  BEFORE INSERT OR UPDATE on offering
  FOR EACH ROW
DECLARE
  isFound NUMBER;
BEGIN
  SELECT 1 INTO isFound FROM DUAL WHERE EXISTS (
    SELECT * FROM Course c
    WHERE c.courseId = :new.courseId AND c.duration = 5);
  IF EXTRACT(MONTH FROM :new.startDate) = 12 
    THEN RAISE_APPLICATION_ERROR(-20001, 'Courses of five days duration cannot be run in December');
  END IF;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    NULL;
END;
于 2013-08-09T13:25:31.573 回答
1

除非您创建一个隐藏两个表的可更新视图,否则无法将一个触发器链接到两个表,从而映射所有应用程序代码以使用此视图。但此解决方案仅在您从头开始开发新应用程序时才有用。

如果您的目标是将代码仅保存在一个地方,则使用存储过程或包并从每个触发器中调用它。

create or replace procedure CheckDuration(
  pStartdate in date, 
  pDuration  in number
)
is
begin

  if( (extract(month from pStartDate) = 12) and (pDuration = 5) ) then

    raise_application_error(-20001, 
      'Courses of five days duration cannot be run in December'
    );

  end if;

end;
/

CREATE OR REPLACE TRIGGER course_BIU
BEFORE INSERT OR UPDATE ON course for each row
begin

  for cCheck in (
    select o.StartDate from offering o where o.courseId = :new.courseId
  ) loop
    CheckDuration(cCheck.StartDate, :new.Duration);
  end loop;

end;
/

CREATE OR REPLACE TRIGGER offering_BIU
BEFORE INSERT OR UPDATE ON offering for each row
begin

  for cCheck in (
    select c.Duration from course c where c.courseId = :new.courseId
  ) loop
    CheckDuration(:new.StartDate, cCheck.Duration);
  end loop;

end;

对于更通用的解决方案,您可以将参数传递给存储过程course%rowtypeoffering%rowtype在内部执行各种检查。

于 2013-08-08T16:51:06.117 回答