DatabaseProgramming: AwardMilePoints.sql

File AwardMilePoints.sql, 1.1 KB (added by 231044, 6 days ago)
Line 
1create or replace function AwardMilePoints()
2returns trigger as $$
3declare
4 ArrivedStatusID int;
5 BoardedStatusID int;
6begin
7 select id
8 into strict ArrivedStatusID
9 from flightstatus
10 where name = 'Arrived';
11
12 select id
13 into strict BoardedStatusID
14 from ticketstatus
15 where name = 'Boarded';
16
17 if new.statusid = ArrivedStatusID
18 and old.statusid is distinct from ArrivedStatusID then
19 update passenger p
20 set milepoints = milepoints + (
21 sf.distance *
22 case sc.name
23 when 'First' then 3
24 when 'Business' then 2
25 else 1
26 end
27 )
28 from ticket t
29 join scheduledflight sf on sf.id = new.scheduleid
30 join seatclass sc on sc.id = t.seatclassid
31 where t.flightid = new.id
32 and t.ticketstatusid = BoardedStatusID
33 and p.id = t.passengerid;
34 end if;
35
36 return new;
37end;
38$$ language plpgsql;
39
40create trigger AwardMilePoints
41after update of statusid on flight
42for each row execute function AwardMilePoints();
43