-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06 Stored_Procedure_ and _Trigger.sql
More file actions
44 lines (33 loc) · 1.07 KB
/
06 Stored_Procedure_ and _Trigger.sql
File metadata and controls
44 lines (33 loc) · 1.07 KB
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
33
34
35
36
37
38
39
40
41
42
43
-- Creating a Stored Procedure
-- Connect to the PostgreSQL database
-- Create the table keyvalue
CREATE TABLE keyvalue (
id SERIAL,
key VARCHAR(128) UNIQUE,
value VARCHAR(128) UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY(id)
);
-- Add a trigger function to automatically update the updated_at column
-- Create the trigger function
CREATE OR REPLACE FUNCTION trigger_set_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Create the trigger that fires the trigger function on UPDATE
CREATE TRIGGER set_updated_at
BEFORE UPDATE ON keyvalue
FOR EACH ROW
EXECUTE FUNCTION trigger_set_updated_at();
/* Check the details of the stored procedure
\df trigger_set_updated_at
List of functions
Schema | Name | Result data type | Argument data types | Type
--------+------------------------+------------------+---------------------+------
public | trigger_set_updated_at | trigger | | func
(1 row)
*/