简体   繁体   中英

pl sql trigger total

I want to create a trigger to calculate the subtotal for each row that is inserted into SALESORDERDETAIL. Subtotal is quantity * price. Can somebody please help me understand how to go about this?

I believe all of the necessary information is in the SALESORDERDETAIL. I have used a trigger in conjunction with a sequence before, but I have not used trigger for anything else. Do I need a procedure and execution each time? How do I write those? Any help is appreciated as I've been stuck on this for the last day. Thank you!

drop table SALESORDERDETAIL;

create table SALESORDERDETAIL (
SONo CHAR(9), -- sales order number
ItemID char(8), -- item being ordered (finished goods)
SOquantity number(5), -- quantity of the item being ordered
Price Number(10,2), -- unit price of each item
subtotal Number(10,2), -- sales order detail (line) subtotal
constraint SOD_pk primary key(SONo,ItemID),
constraint SOD_FG_FK foreign key(ItemID) references FinishedGoods(itemid),
constraint SOD_SO_FK foreign key(SONo) references SalesOrders(SONo)
);

Insert into SALESORDERDETAIL (SONO,ITEMID,SOQUANTITY,PRICE,SUBTOTAL) values
('SO1000001','FG000001',100,10,'');
Insert into SALESORDERDETAIL (SONO,ITEMID,SOQUANTITY,PRICE,SUBTOTAL) values
('SO1000001','FG000002',50,2,'');

commit;

Assuming this is Oracle? If so, consider a virtual column instead of a trigger:

...
subtotal     AS (soquantity * price),
...

... but if you still want a trigger, it would look somewhat like this:

 CREATE OR REPLACE TRIGGER SALESORDERDETAIL_before BEFORE INSERT OR UPDATE ON SALESORDERDETAIL FOR EACH ROW BEGIN :new.subtotal := :new.soquantity * :new.price; END; / 

I'm not a fan of less elegant solutions, but looks like it's for education, not for problem solving, so good luck.

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