source: database/Advanced Database Developement/Triggers/Automatic update of product availability after an order.txt@ 06ebe74

finki-main main
Last change on this file since 06ebe74 was 62b2964, checked in by Klimentina Efremova <klimentina08642@…>, 2 weeks ago

Project Handcraft Marketplace

  • Property mode set to 100644
File size: 1.1 KB
Line 
1CREATE OR REPLACE FUNCTION update_product_availability()
2RETURNS TRIGGER
3LANGUAGE plpgsql
4AS $$
5BEGIN
6 -- When a product is newly added to an order,
7 -- decrease the available quantity.
8 IF TG_OP = 'INSERT' THEN
9
10 UPDATE sells
11 SET quantity = quantity - (
12 SELECT o.quantity
13 FROM "order" o
14 WHERE o.order_num = NEW.order_num
15 )
16 WHERE code = NEW.code;
17
18 -- If the product/order entry is modified,
19 -- restore the old quantity and subtract the new quantity.
20 ELSIF TG_OP = 'UPDATE' THEN
21
22 UPDATE sells
23 SET quantity = quantity
24 + (
25 SELECT o.quantity
26 FROM "order" o
27 WHERE o.order_num = OLD.order_num
28 )
29 - (
30 SELECT o.quantity
31 FROM "order" o
32 WHERE o.order_num = NEW.order_num
33 )
34 WHERE code = NEW.code;
35
36 END IF;
37
38 RETURN NULL;
39END;
40$$;
41
42
43CREATE TRIGGER trg_update_product_availability
44AFTER INSERT OR UPDATE
45ON includes
46FOR EACH ROW
47EXECUTE FUNCTION update_product_availability();
Note: See TracBrowser for help on using the repository browser.