【问题标题】:Oracle-Trigger for testing the number of students in a class用于测试班级学生人数的 Oracle-Trigger
【发布时间】:2020-09-18 19:47:10
【问题描述】:

我正在尝试创建一个限制组中学生人数的前插入触发器,我的意思是,如果组中的学生人数大于 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 新手,不知道如何使用它。

非常感谢您!

【问题讨论】:

    标签: oracle plsql count database-trigger


    【解决方案1】:

    您需要使用Statement Trigger,在其中检查class_id 是否有任何组违反规则,而不是Row 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;
    

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      相关资源
      最近更新 更多