Skip to content

Commit 431b5b4

Browse files
[ADD] Raise history sample
1 parent a17cbf7 commit 431b5b4

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

classes/33-store-procedures.sql

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,43 @@ CALL insert_region_proc(5, 'Central America');
1717

1818
SELECT *
1919
FROM regions;
20+
21+
-- Create a raise history
22+
CREATE OR REPLACE PROCEDURE controlled_raise (percentage NUMERIC) AS $$
23+
DECLARE
24+
real_percentage NUMERIC(8,2);
25+
total_employees INT;
26+
BEGIN
27+
real_percentage = percentage / 100;
28+
29+
-- Save the historical records
30+
INSERT INTO raise_history (date, employee_id, base_salary, amount, percentage)
31+
SELECT
32+
CURRENT_DATE,
33+
employee_id,
34+
salary,
35+
max_raise(employee_id) * real_percentage,
36+
percentage
37+
FROM employees;
38+
39+
-- Update the employees table
40+
UPDATE employees
41+
SET salary = salary + (max_raise(employee_id) * real_percentage);
42+
43+
SELECT COUNT(*) INTO total_employees
44+
FROM employees;
45+
46+
RAISE NOTICE 'Affected % employees', total_employees
47+
48+
COMMIT;
49+
50+
END;
51+
$$ LANGUAGE plpgsql;
52+
53+
CALL controlled_raise(1);
54+
55+
SELECT *
56+
FROM employees;
57+
58+
SELECT *
59+
FROM raise_history;

resources/12-raise-history.sql

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
DROP TABLE IF EXISTS "public"."raise_history";
2+
-- This script only contains the table creation statements and does not fully represent the table in the database. It's still missing: indices, triggers. Do not use it as a backup.
3+
4+
-- Sequence and defined type
5+
CREATE SEQUENCE IF NOT EXISTS raise_history_id_seq;
6+
7+
-- Table Definition
8+
CREATE TABLE "public"."raise_history" (
9+
"id" int4 NOT NULL DEFAULT nextval('raise_history_id_seq'::regclass),
10+
"date" date,
11+
"employee_id" int4,
12+
"base_salary" numeric(8,2),
13+
"amount" numeric(8,2),
14+
"percentage" numeric(4,2),
15+
PRIMARY KEY ("id")
16+
);

0 commit comments

Comments
 (0)