CREATE OR REPLACE FUNCTION seattleInsert RETURNS trigger AS DECLARE re

 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
CREATE OR REPLACE FUNCTION seattleInsert()
RETURNS trigger AS $$
DECLARE
result RECORD;
BEGIN
SELECT count(*) as t_count, d.department_id as depID INTO result
FROM departments d, locations l, countries c
WHERE l.location_id=d.location_id AND
l.country_id=c.country_id AND
c.country_name='United States of America' AND
l.city='Seattle' AND
d.department_name=new.department_name
GROUP BY d.department_id;
if result.t_count > 0 then
INSERT INTO employees(first_name, last_name, hire_date, salary, department_id) VALUES (
new.first_name,
new.last_name,
new.hire_date,
new.salary,
result.depID);
RETURN new;
END IF;
RETURN NULL;
END;
$$ LANGUAGE PLPGSQL SECURITY DEFINER;
DROP TRIGGER seattle_employees_insert ON seattle_employees;
CREATE TRIGGER seattle_employees_insert INSTEAD OF insert on
seattle_employees FOR EACH ROW EXECUTE
PROCEDURE seattleInsert();