-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTriggers.sql
109 lines (96 loc) · 2.23 KB
/
Triggers.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
-- Trigger to update the inventory when an order is placed
CREATE OR REPLACE TRIGGER UPDATE_INVENTORY BEFORE
INSERT ON ORDERS
FOR EACH ROW
DECLARE
CURSOR ITEMS IS
SELECT
CI.P_ID,
CI.QTY
FROM
CART_ITEMS CI,
CART
WHERE
CI.CART_ID = CART.CART_ID
AND CART.BUYER_ID = :NEW.BUYER_ID;
THIS_ITEM ITEMS%ROWTYPE;
NEW_QTY NUMBER := 0;
OLD_QTY NUMBER;
BEGIN
OPEN ITEMS;
LOOP
FETCH ITEMS INTO THIS_ITEM;
EXIT WHEN ( ITEMS%NOTFOUND );
SELECT
QTY
INTO OLD_QTY
FROM
PRODUCT
WHERE
P_ID = THIS_ITEM.P_ID;
NEW_QTY := OLD_QTY - THIS_ITEM.QTY;
IF NEW_QTY < 0 THEN
RAISE_APPLICATION_ERROR(
-20000,
'Not enough stock'
);
END IF;
UPDATE PRODUCT
SET
QTY = NEW_QTY
WHERE
P_ID = THIS_ITEM.P_ID;
END LOOP;
CLOSE ITEMS;
END;
-- Trigger to reset a user's cart after an order is placed
CREATE OR REPLACE TRIGGER EMPTY_CART AFTER
INSERT ON ORDERS
FOR EACH ROW
DECLARE
CID CART.CART_ID%TYPE;
BEGIN
SELECT
CART_ID
INTO CID
FROM
CART
WHERE
BUYER_ID = :NEW.BUYER_ID;
DELETE FROM CART_ITEMS
WHERE
CART_ID = CID;
UPDATE CART
SET
CART.TOTAL_QTY = 0,
CART.TOTAL_PRICE = 0
WHERE
CART_ID = CID;
END;
-- Trigger to update total quantity and total price of the cart when an item is added
CREATE OR REPLACE TRIGGER UPDATE_CART_DETAILS AFTER
INSERT ON CART_ITEM S
FOR EACH ROW
DECLARE
ITEM_PRICE PRODUCT.PRICE%TYPE;
ADDED_PRICE PRODUCT.PRICE%TYPE;
BEGIN
UPDATE CART
SET
TOTAL_QTY = :NEW.QTY + TOTAL_QTY
WHERE
CART_ID = :NEW.CART_ID;
SELECT
PRICE
INTO ITEM_PRICE
FROM
PRODUCT
WHERE
P_ID = :NEW.P_ID;
ADDED_PRICE := ITEM_PRICE * :NEW.QTY;
UPDATE CART
SET
TOTAL_PRICE = TOTAL_PRICE + ADDED_PRICE
WHERE
CART_ID = :NEW.CART_ID;
END;