I have to create a trigger (not procedure) to update subtotal, shipping_charge, tax and total_amount. Basically, all these attributes come from orders table, and each of them involve some calculations. subtotal = Unit_Price * QTY where Unit_Price comes from Product table, and QTY comes from Orderline table. The problem is when the orders table was first created, there were no exp_ship and exp_receive dates so I had to alter the orders table to add these new columns. I am not allowed to change the old data. So, I created a copy of the Orders table for records, and have been working on the original orders table. Now, every time a new order is made, I have to write a trigger that would calculate the subtotal, shipping_charge, tax and total_amt, and update these fields in the orders table.
I tried the following code, but there are so many errors. I am sorry but I’m trying this for the first time. I am still in the learning process. The way I have to do it is by creating a view and using an Instead of trigger on the view. That is, get the information from the view and update the order table.
DROP VIEW ORDERS_V;
CREATE VIEW ORDERS_V AS
SELECT * FROM ORDERS;
CREATE OR REPLACE TRIGGER update_orders
INSTEAD OF INSERT ON ORDERS_V
FOR EACH ROW
DECLARE
SHIPPING_COST NUMBER(6,3);
BEGIN
SELECT UNIT_PRICE INTO UNIT_PRICE FROM PRODUCT;
SELECT QTY INTO QTY FROM ORDERLINE;
SELECT SHIPPING_METHOD INTO SHIPPING_METHOD FROM ORDERS;
SELECT SUBTOTAL INTO SUBTOTAL FROM ORDERS;
UPDATE ORDERS
SET SUBTOTAL = UNIT_PRICE * QTY;
IF SHIPPING_METHOD = 'GROUND' THEN
shipping_cost := .05;
ELSIF SHIPPING_METHOD = '1 DAY' THEN
shipping_cost := .15;
ELSIF SHIPPING_METHOD = '2 DAY' THEN
shipping_cost := .10;
ELSE
shipping_cost := 0;
END IF;
UPDATE ORDERS
SET shipping_charge = SUBTOTAL * shipping_cost;
END;
/
At the moment your trigger is working with whole tables. This is obviously not what you want. So you need to add WHERE clauses to those statements, in order to restrict the activity to the required rows. In triggers we use the
:NEW.notation to get the values of columns in the triggering table. Something like this:Another syntax correction: we can include several columns in an UPDATE. This is better than issuing multiple statements.
I did intend to re-write your whole trigger. However your logic remains confusing (you will recall I suggested you clarify things in my answer to your previous question). Things you need to straighten out:
Your trigger fires on INSTEAD OF INSERT but your code UPDATES existing records in the underlying table. Huh?
You are selecting from ORDERLINE. The expected data model would be an ORDER to have one or more LINES. If this is so, your code ought to handle multiple rows for ORDERLINE (and I guess PRODUCT).
You select SUBTOTAL from the underlying table although subsequently you appear to overwrite the value. Then you use SUBTOTAL in a calculation: which value of SUBTOTAL do you think you’re using?