【问题标题】:Oracle trigger to update a field (field+1 and field -1) when inserting and deleting插入和删除时Oracle触发器更新一个字段(字段+1和字段-1)
【发布时间】:2018-11-21 11:33:28
【问题描述】:

我需要创建一个触发器,在插入或删除员工(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 语句或为商店声明变量,但我不清楚,所以我只是在这里解析了我最确定的代码)。

【问题讨论】:

标签: oracle triggers


【解决方案1】:

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

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;

【讨论】:

    猜你喜欢
    • 2010-12-22
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 2011-02-27
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    相关资源
    最近更新 更多