Guest User

Untitled

a guest
Sep 8th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. CREATE TABLE discount_group (
  2.         customer_group_id INTEGER DEFAULT NULL,
  3.         customer_id INTEGER DEFAULT NULL,
  4.         product_group_id INTEGER DEFAULT NULL,
  5.         product_id INTEGER DEFAULT NULL,
  6.         discount REAL NOT NULL
  7. );
  8.  
  9. ALTER TABLE discount_group
  10. ADD CONSTRAINT customer_group_discount_group FOREIGN KEY (customer_group_id)
  11. REFERENCES customer_group(id) ON UPDATE CASCADE ON DELETE CASCADE;
  12.  
  13. ALTER TABLE discount_group
  14. ADD CONSTRAINT customer_discount_group FOREIGN KEY (customer_id)
  15. REFERENCES customer(id) ON UPDATE CASCADE ON DELETE CASCADE;
  16.  
  17. ALTER TABLE discount_group
  18. ADD CONSTRAINT product_group_discount_group FOREIGN KEY (product_group_id)
  19. REFERENCES product_group(id) ON UPDATE CASCADE ON DELETE CASCADE;
  20.  
  21. ALTER TABLE discount_group
  22. ADD CONSTRAINT product_discount_group FOREIGN KEY (product_id)
  23. REFERENCES product(id) ON UPDATE CASCADE ON DELETE CASCADE;
  24.  
  25.  
  26.  
  27. CREATE OR REPLACE FUNCTION add_discount(
  28.         customer_group_id INTEGER,
  29.         customer_id INTEGER,
  30.         product_group_id INTEGER,
  31.         product_id INTEGER,
  32.         discount REAL
  33. )
  34. RETURNS INTEGER AS $$
  35. DECLARE points INTEGER DEFAULT 0;
  36. BEGIN
  37.     IF customer_group_id IS NOT NULL OR customer_id IS NOT NULL THEN
  38.         points := points + 1;
  39.     END IF;
  40.     IF product_group_id IS NOT NULL OR product_id IS NOT NULL THEN
  41.         points := points +1;
  42.     END IF;
  43.  
  44.     IF points < 2 THEN
  45.         RAISE EXCEPTION 'Either no customer_group_id/customer_id
  46.                         or product_group_id/product_id was specified';
  47.     END IF;
  48.     RETURN 0;
  49. END;
  50. $$ LANGUAGE plpgsql;
Add Comment
Please, Sign In to add comment