创建将更新属性的触发器

Creating a trigger that will update an attribute

问题:编写一个触发器,每次更新 table 行(插入、更新或删除新行)时都会更新发票小计。包括用于测试插入、更新和删除的 SQL 语句。

我发现很难正确理解触发器,我也不知道为什么。我理解它的基本概念(至少我认为我理解)但我似乎无法理解如何回答我的问题。下面的代码是我试图回答上面的问题:

create or replace trigger update_subtotal
after insert or update or delete 
on invoice
for each row

begin

insert into line ('inv_number', 'line_number', 'p_code', 'line_units', 'line_price')
values ('1009', '3', '12345-6t', '1', '123.45');

end;

select * from line;

在 运行 这段代码之后我遇到了这些错误:

Errors: TRIGGER UPDATE_SUBTOTAL
Line/Col: 3/1 PL/SQL: SQL Statement ignored
Line/Col: 3/19 PL/SQL: ORA-00928: missing SELECT keyword
Line/Col: 17/1 PLS-00103: Encountered the symbol "SELECT"

我正在使用 Oracle Live。

简而言之:帮助。

你这个概念好像反了。 invoice table 需要在 line 更改时更新——因此 line 需要触发器,而对 invoice 的更改是 update。那将是这样的:

create or replace trigger trg_line_update_subtotal
after insert or update or delete 
on line
for each row
begin
    update invoice i
        set total = coalesce(i.total, 0) +
                    coalesce(:new.line_Units * :new.line_price, 0) -
                    coalesce(:old.line_Units * :old.line_price, 0)
        where i.inv_number = coalesce(:new.inv_number, :old.inv_number);
end;