CREATE or REPLACE PROCEDURE UPDATE_SUBTOTAL is

v_order_no orderline.order_no%type;

v_subtotal   number(15); 

CURSOR product_orderline_cur is

SELECT ol.order_no, sum(p.unit_price * ol.qty) as subtotal

from product p, orderline ol

where p.product_no = ol.product_no

group by ol.order_no;

BEGIN

OPEN product_orderline_cur;

LOOP

    FETCH product_orderline_cur into v_order_no, v_subtotal;

    EXIT when product_orderline_cur%notfound;

    -- store subtotal in orders table

    UPDATE orders

    SET subtotal = v_subtotal  

    WHERE order_no = v_order_no;

END LOOP;

--an order may be created but no orderlines added yet,insert a 0

UPDATE orders

SET subtotal = 0

WHERE subtotal is null;

CLOSE product_orderline_cur;

END;

/
show errors;
0
tbrown 6 Мар 2011 в 08:30

1 ответ

CREATE OR REPLACE TRIGGER orders_before_update
BEFORE UPDATE ON orders
    FOR EACH ROW

DECLARE v_sum INT;

BEGIN

    SELECT SUM(p.unit_price * ol.qty)
    INTO v_sum
    FROM product p INNER JOIN orderline ol
      ON p.product_no = ol.product_no
    WHERE ol.order_no = :new.order_no;

    :new.subtotal := COALESCE(v_sum, 0);
END;
0
The Scrum Meister 6 Мар 2011 в 08:38