-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDDL_triggers.sql
82 lines (69 loc) · 2.35 KB
/
DDL_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
-- INSERT TRIGGER: updates total price of a leasing when bike is added to it
CREATE OR REPLACE TRIGGER TRG_LEASING_BIKE_INSERT_PRE
BEFORE INSERT ON leasing_bike
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
DECLARE
leasing_rec leasing%rowtype;
bikePrice bike.pricePerDay%type;
bikeLeasingPrice bike.pricePerDay%type;
newTotal leasing.total%type;
BEGIN
SELECT * INTO leasing_rec FROM leasing
WHERE lid = :NEW.leasing;
SELECT pricePerDay INTO bikePrice FROM bike
WHERE bid = :NEW.bike;
bikeLeasingPrice := (leasing_rec.endDate - leasing_rec.startDate) * bikePrice;
IF(leasing_rec.total IS NULL) THEN
newTotal := bikeLeasingPrice;
ELSE
newTotal := leasing_rec.total + bikeLeasingPrice;
END IF;
UPDATE leasing
SET total = newTotal
WHERE lid = leasing_rec.lid;
END;
/
CREATE OR REPLACE TRIGGER TRG_PART_INSERT_UPDATE_PRE
BEFORE INSERT OR UPDATE ON part
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
DECLARE
leasing_rec leasing%rowtype;
partPrice part.pricePerDay%type;
partLeasingPrice part.pricePerDay%type;
newTotal leasing.total%type;
BEGIN
IF (:NEW.leasing IS NOT NULL) THEN
SELECT * INTO leasing_rec FROM leasing
WHERE lid = :NEW.leasing;
partPrice := :NEW.pricePerDay;
partLeasingPrice := (leasing_rec.endDate - leasing_rec.startDate) * partPrice;
IF(leasing_rec.total IS NULL) THEN
newTotal := partLeasingPrice;
ELSE
newTotal := leasing_rec.total + partLeasingPrice;
END IF;
UPDATE leasing
SET total = newTotal
WHERE lid = leasing_rec.lid;
END IF;
END;
/
-- UPDATE TRIGGER: recalculates total price of a leasing when its endDate is updated
CREATE OR REPLACE TRIGGER TRG_LEASING_PRE_UPDATE_ENDDATE
BEFORE UPDATE OF endDate ON leasing
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
DECLARE
totalBikePricePerDay bike.pricePerDay%type;
totalPartPricePerDay part.pricePerDay%type;
BEGIN
SELECT SUM(pricePerDay) INTO totalBikePricePerDay FROM leasing_bike
INNER JOIN bike ON bike.bid = leasing_bike.bike
WHERE leasing = :NEW.lid;
SELECT SUM(pricePerDay) INTO totalPartPricePerDay FROM part
WHERE leasing = :NEW.lid;
:NEW.total := (:NEW.endDate - :OLD.startDate) * (totalBikePricePerDay + totalPartPricePerDay);
END;
/