oracle - 插入和删除时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 语句或为商店声明一个变量,但我不清楚,所以我只是在这里解析了我最确定的代码)。
解决方案
这可能是让您的触发器工作所需的全部内容:
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;
推荐阅读
- javascript - 在localStorage中选中复选框时如何存储直通?
- java - Spring MockMvc:断言Json字段是空数组或不存在
- c# - 如何按不包括第一行的列对数据进行排序
- angular - 如何在输入上重新应用角管
- java - 为什么在通过 OSHI API 从传感器检索信息时会发生这种情况?
- typescript - 如何在 VS Code 上使用 typescript 调试feathersjs?
- reactjs - React 钩子更新多个状态变量
- mysql - SQLSTATE[HY000] [1045] 用户 'qualitym_yaseen'@'localhost' 的访问被拒绝(使用密码:YES)
- angular - 如何获取 mat-table 的当前元素并放入代码的另一部分?
- python - 如何检查参数是否传递给函数?