如何创建更新触发器

时间:2014-01-21 11:50:23

标签: sql oracle triggers transactions

我正在尝试创建一个触发器,它将在订单表中输入商品时运行,product表中的数量应该减少

create or replace trigger quantity_dicr after update of quantity on products for each  row
declare
  quantity float;
  begin 
      select quantity into quantity from products where o_id = :new.o_id;
      set quantity = quantity + :new.quantity ,
      where o_id= :new.o_id;
  end quantity_dicr;

create table products(
prod_id numeric not null,
prod_name varchar2(50) not null,
quantity numeric not null,
price numeric not null,
constraint prod_id_pk primary key(prod_id)
)
create table orders 
(
prod_id numeric not null,
o_id numeric not null,
quantity numeric not null,
o_sum numeric not null,
constraint fk_products  foreign key (prod_id) references products(prod_id),
constraint orders_pk  primary key (o_id) )
)

它给了我这些错误

Error(4,64): PLS-00049: bad bind variable 'NEW.O_ID'
Error(5,7): PL/SQL: SQL Statement ignored
Error(5,11): PL/SQL: ORA-00922: missing or invalid option
Error(6,19): PLS-00049: bad bind variable 'NEW.O_ID'

任何可以掩饰轻微错误的帮助都会有所帮助

2 个答案:

答案 0 :(得分:0)

我认为一定是这个:

create or replace trigger quantity_dicr 
   after update of quantity on orders 
   for each row

必须在表格订单而不是表格产品上定义触发器。

顺便说一句,如果放置订单会发生什么(即INSERT成订单)。我认为这也应该更新产品数量。

答案 1 :(得分:0)

你的错误就在这里

create or replace trigger quantity_dicr after update of quantity on products for each  row
declare
  quantity float;
 begin 
  select quantity into quantity from products where o_id = :new.o_id;
  set quantity = quantity + :new.quantity ,
  where o_id= :new.o_id; --Don't have field O_ID in table products
end quantity_dicr;

你可以这样做。

CREATE OR REPLACE TRIGGER quantity_dicr AFTER UPDATE ON orders FOR EACH ROW
  UPDATE products SET quantity = quantity - :NEW.quantity WHERE prod_id = :NEW.prod_id;
END quantity_dicr;

请阅读此questionofficial documentation以获取更多信息。