SQL触发器在插入给出错误的值之前进行验证

时间:2013-11-20 06:42:18

标签: sql triggers oracle11g

我在Oracle Express Edition的数据库中为表创建了一个触发器,它有两个属性:room_id,roll_no。 room_id是从另一个名为ROOM的表中引用的,roll_no是从另一个名为STUDENT的表中引用的。

CREATE OR REPLACE TRIGGER  "STUDENT_ROOM_T1" 
BEFORE
insert on "STUDENT_ROOM"
for each row
begin
DECLARE
room_change_limit EXCEPTION;
capacity_exceeding EXCEPTION;

BEGIN

IF((select no_of_room_changes_this_year from student where roll_no = :NEW.roll_no) = 2)
THEN
RAISE room_change_limit;
END IF;

IF((select count(roll_no) from student_room where room_id = :NEW.room_id group by room_id) + 1 > (select capacity from room where room_id = :NEW.room_id))
THEN
RAISE capacity_exceeding;
END IF;

update student
set no_of_room_changes_this_year = no_of_room_changes_this_year + 1
where roll_no = :NEW.roll_no;

EXCEPTION

WHEN room_change_limit THEN
Raise_application_error(-20324, 'Student has reached room change limit for this year!');

WHEN capacity_exceeding THEN
Raise_application_error(-20326, 'Capacity of room has been reached! Please try another room.');

end;
/
ALTER TRIGGER  "STUDENT_ROOM_T1" ENABLE;

我有两个错误:

PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: ( - + 
case mod new not null
PLS-00103: Encountered the symbol ")" when expecting one of the following: . ( * @ % & - + ; /
at for mod remainder rem and or group having intersect minus order start uni

谁能告诉我这里出了什么问题以及如何纠正?我无法理解为什么我会收到这个错误。

1 个答案:

答案 0 :(得分:1)

IF语句不接受这样的subselect。声明一个变量,执行SELECT INTO然后执行IF测试。

示例:

DECLARE
 v_no_of_room_changes_this_year NUMBER;
BEGIN

 SELECT no_of_room_changes_this_year INTO v_no_of_room_changes_this_year 
 FROM student WHERE roll_no = :NEW.roll_no;

 IF( v_no_of_room_changes_this_year  = 2 )
 THEN
  RAISE room_change_limit;
 END IF;

...