创建将更新属性的触发器

时间:2021-04-04 00:33:47

标签: sql oracle triggers

问题:编写一个触发器,该触发器将在每次更新行表(插入、更新或删除新行)时更新发票小计。包括用于测试插入、更新和删除的 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。

简而言之:帮助。

1 个答案:

答案 0 :(得分:2)

你的概念好像倒退了。 invoice 表需要在 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;
相关问题