首页 > 解决方案 > 用于测试班级学生人数的 Oracle-Trigger

问题描述

我正在尝试创建一个限制组中学生人数的前插入触发器,我的意思是,如果组中的学生人数大于 5,则用户不能在同一组中引入任何其他记录,但他在其他少于 5 名学生的情况下可以。

在表中,我有以下信息:

在此处输入图像描述

因此触发器应该允许在除第二行之外的所有行中添加记录,因为那里已经有 5 个学生。

我尝试了以下代码:

create or replace trigger groups_capacity
 before insert on s183410_group
  for each row

  declare
   counter INTEGER;

 BEGIN 
    select count(*)into counter from s183410_group group by class_id;

        if counter>5 and :old.class_id=:new.class_id then
            raise_application_error(-20002,'This class is full.There cannot be more than 5 students in the same group.');
        end if;

END;

我认为计数器不会改变每一行的值。我是 oracle 的新手,不知道如何使用它。

非常感谢您提前!!

标签: oracleplsqlcountdatabase-trigger

解决方案


您需要使用 aStatement Trigger来检查 class_id 的任何组是否违反规则,而不是 aRow Level Trigger为了不发生变异触发错误:

CREATE OR REPLACE TRIGGER groups_capacity
  AFTER INSERT ON s183410_group

DECLARE
  counter INT;
BEGIN
  SELECT MAX(COUNT(*)) INTO counter FROM s183410_group GROUP BY class_id;

  IF counter > 5 THEN
    raise_application_error(-20002,
                            'This class is full.
                             There cannot be more than 5 students in the same group.');
  END IF;
END;

推荐阅读