简体   繁体   中英

Oracle: After update Trigger

I have 3 tables:

Category(CategoryId, Name)
Product(ProductId, Name, Description, CategoryId)
OrderItem(OrderId, OrdinalNumber, ProductId, CategoryId)

I want to create an AFTER UPDATE trigger that changes CategoryId (based on new ProductId) in OrderItem after update of ProductId in OrderItem .

Can somebody help with this trigger?

Duplicating the category ID in the order line isn't something you'd usually want to do, but if you're set on that, you need a 'before' trigger, not an 'after' one - since you need to change a value in the row being updated:

create or replace trigger orderitem_cat_trig
before insert or update on orderitem
for each row
begin
  select categoryid
  into :new.categoryid
  from product
  where productid = :new.productid;
end;
/

I've made it both insert and update on the assumption you'll want to set the value for new order items too.

Unless you like database deadlocks, general performance issues, data corruption and unpredictable results, this type of updates is not advisable. If your performance is a problem, check indexes and queries. Do not replicate your columns in tables, especially not when they're part of an foreign key. I'm not the dogmatic type, but in this case I will not budge ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM