如何让Trigger像外键一样工作?

时间:2017-11-10 20:53:49

标签: sql database firebird

我需要使用触发器创建外键而不是像这样使用alter table:

 alter table WORKER
      add constraint WORKER_idDepartment_FK
      foreign key (idDepartment)
      references DEPARTMENT (idDepartment);

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:2)

在极少数情况下,您放弃标准的FOREIGN KEY机制以支持其他内容。例如,我们有一个真正庞大的数据库,其中创建了数十个FK。这些外键占用了数百兆的磁盘空间。就其本质而言,它们引用的表记录数比主表中的数量少10000-100000倍。切换到触发器以支持数据完整性后,我们减少了db文件大小的显着性并获得了一些整体性能提升。

这样的外键:

 alter table WORKER
      add constraint WORKER_idDepartment_FK
      foreign key (idDepartment)
      references DEPARTMENT (idDepartment);

可以使用两个触发器进行模拟:

 CREATE TRIGGER aiu_worker FOR WORKER
   AFTER INSERT OR UPDATE
   POSITION 0
 AS BEGIN
   IF (NOT EXISTS(
      SELECT idDepartment 
      FROM DEPARTMENT 
      WHERE idDepartment = NEW.idDepartment)) THEN
    EXCEPTION my_exception 'There is no department with id=' ||
      NEW.idDepartment;
 END

 CREATE TRIGGER ad_department FOR DEPARTMENT
   AFTER DELETE
   POSITION 0
 AS BEGIN
   IF (EXISTS (
       SELECT idDepartment 
       FROM WORKER 
       WHERE idDepartment = OLD.idDepartment)) THEN
   BEGIN
     EXCEPTION my_exception 'Can not delete record';
   END
 END

您可以轻松调整这些触发器以实现CASCADE规则或支持可空字段。