具有条件更新的Oracle SQL触发器基于单独表中的信息

时间:2016-09-29 21:00:45

标签: sql triggers oracle-sqldeveloper plsqldeveloper

我有两张桌子:

  • cost_bank(这是我想要触发的地方)
  • master_data(此表包含我需要检查的信息)

我想在插入&#34;之后构建一个&#34; cost_bank上的触发器,当新插入的cost_bank.work_code位于带有master_data的{​​{1}}表格中时运行。如果这种情况属实,我希望触发器仅在master_data.charge_type = 'EX'中使用ID的{​​{1}}的值更新新添加的行(可由cost_bank指定)。< / p>

这是我到目前为止所做的:

master_data.r_cost_center

赞赏任何见解

1 个答案:

答案 0 :(得分:0)

如果要修改同一个表,则需要之前插入触发器:

CREATE OR REPLACE TRIGGER expense_charge_cost_center
 BEFORE INSERT ON cost_bank FOR EACH ROW
 WHEN (new.work_code in (select work_code from master_data where charge_type = 'EX'))
BEGIN
   select r_cost_center into :new.cost_center
   from master_data
   where work_code = new.work_code;
END;

实际上,我不确定子查询是否与when一起使用,因此您可能需要:

CREATE OR REPLACE TRIGGER expense_charge_cost_center
 BEFORE INSERT ON cost_bank FOR EACH ROW
BEGIN
   if (new.work_code in (select work_code from master_data where charge_type = 'EX')) then
       select r_cost_center into :new.cost_center
       from master_data
       where work_code = new.work_code;  -- I'm guessing you also want charge_type = 'EX'
   end if;
END;