首页 > 解决方案 > Using Trigger to maintain referential integrity

问题描述

I am trying to write a SQL trigger for any insert on the relation Section and it should ensure that the time slot id value that is being inserted is valid.

The Section relation

Thanks in advance!

标签: oracleplsqldatabase-triggerreferential-integrity

解决方案


让我们首先说明使用触发器来强制关系完整性而不是外键约束是最糟糕的做法。RI 触发器很慢,它们不能很好地扩展,它们不能在多用户环境中工作,它们会在必须维护代码的可怜的 blighter 中引起不必要的头疼。

因此,这是一个正常运行的最差实践触发器的样子:

create or replace trigger section_timeslot_trg 
before insert or update on section
for each row
declare
    l_id timeslot.timeslot_id%type;
begin
    select ts.timeslot_id
    into l_id
    from timeslot ts
    where ts.timeslot_id = :new.timeslot_id;
exception
    when no_data_found then
        raise_application_error(-20999, 'Not a valid TIMESLOT_ID: '||:new.timeslot_id);
end;

请记住,在没有外键约束的情况下,需要在 TIMESLOT 上有一个互惠触发器,以防止更新和删除 SECTION 中使用的 TIMESLOT_ID。


推荐阅读