首页 > 解决方案 > 插入和删除时Oracle触发器更新字段(字段+1和字段-1)

问题描述

我需要创建一个触发器,当插入或删除员工(EMPLOYERS TABLE)时,表 SHOPS UPDATE 中的属性 EMPTOTAL。

EMPLOYERS 表有一个名为 SHOP 的字段(和外键)引用 SHOPS 表。

我知道它应该与此类似,但我的练习中没有任何示例涉及超过 1 个表格。

CREATE OR REPLACE TRIGGER UPD_EMPTOTAL BEFORE INSERT OR DELETE ON EMPLOYERS FOR EACH ROW
DECLARE
BEGIN
IF INSERTING THEN
UPDATE SHOPS SET EMPTOTAL=EMPTOTAL+1;
ELSIF DELETING THEN
UPDATE SHOPS SET EMPTOTAL=EMPTOTAL-1;
END IF;

END;

(我已经尝试过其他的事情,比如 UPDATE 语句或为商店声明一个变量,但我不清楚,所以我只是在这里解析了我最确定的代码)。

标签: oracletriggers

解决方案


这可能是让您的触发器工作所需的全部内容:

create or replace trigger upd_emptotal
   before insert or delete on employers
   for each row
declare
begin
   if inserting
   then
      -- Update only shop total for the shop
      -- in the employer record.
      -- :new.shop is the value being inserted in the table.

      update shops
         set emptotal = emptotal + 1
       where shop = :new.shop;
   elsif deleting
   then
      -- Update only shop total for the shop
      -- in the employer record.
      -- :old.shop is the value in the record being deleted.
      update shops
         set emptotal = emptotal - 1
       where shop = :old.shop;
   end if;

end;

推荐阅读