云数据库 GAUSSDB-CREATE TRIGGER:示例

时间:2024-01-23 20:09:25

示例

 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
--创建源表及触发表
postgres=# CREATE TABLE test_trigger_src_tbl(id1 INT, id2 INT, id3 INT);
postgres=# CREATE TABLE test_trigger_des_tbl(id1 INT, id2 INT, id3 INT);

--创建触发器函数
postgres=# CREATE OR REPLACE FUNCTION tri_insert_func() RETURNS TRIGGER AS
           $$
           DECLARE
           BEGIN
                   INSERT INTO test_trigger_des_tbl VALUES(NEW.id1, NEW.id2, NEW.id3);
                   RETURN NEW;
           END
           $$ LANGUAGE PLPGSQL;

postgres=# CREATE OR REPLACE FUNCTION tri_update_func() RETURNS TRIGGER AS
           $$
           DECLARE
           BEGIN
                   UPDATE test_trigger_des_tbl SET id3 = NEW.id3 WHERE id1=OLD.id1;
                   RETURN OLD;
           END
           $$ LANGUAGE PLPGSQL;

postgres=# CREATE OR REPLACE FUNCTION TRI_DELETE_FUNC() RETURNS TRIGGER AS
           $$
           DECLARE
           BEGIN
                   DELETE FROM test_trigger_des_tbl WHERE id1=OLD.id1;
                   RETURN OLD;
           END
           $$ LANGUAGE PLPGSQL;

--创建INSERT触发器
postgres=# CREATE TRIGGER insert_trigger
           BEFORE INSERT ON test_trigger_src_tbl
           FOR EACH ROW
           EXECUTE PROCEDURE tri_insert_func();

--创建UPDATE触发器
postgres=# CREATE TRIGGER update_trigger
           AFTER UPDATE ON test_trigger_src_tbl  
           FOR EACH ROW
           EXECUTE PROCEDURE tri_update_func();

--创建DELETE触发器
postgres=# CREATE TRIGGER delete_trigger
           BEFORE DELETE ON test_trigger_src_tbl
           FOR EACH ROW
           EXECUTE PROCEDURE tri_delete_func();

--执行INSERT触发事件并检查触发结果
postgres=# INSERT INTO test_trigger_src_tbl VALUES(100,200,300);
postgres=# SELECT * FROM test_trigger_src_tbl;
postgres=# SELECT * FROM test_trigger_des_tbl;  //查看触发操作是否生效。

--执行UPDATE触发事件并检查触发结果
postgres=# UPDATE test_trigger_src_tbl SET id3=400 WHERE id1=100;
postgres=# SELECT * FROM test_trigger_src_tbl;
postgres=# SELECT * FROM test_trigger_des_tbl;  //查看触发操作是否生效

--执行DELETE触发事件并检查触发结果
postgres=# DELETE FROM test_trigger_src_tbl WHERE id1=100;
postgres=# SELECT * FROM test_trigger_src_tbl;
postgres=# SELECT * FROM test_trigger_des_tbl;  //查看触发操作是否生效

--修改触发器
postgres=# ALTER TRIGGER delete_trigger ON test_trigger_src_tbl RENAME TO delete_trigger_renamed;

--禁用insert_trigger触发器
postgres=# ALTER TABLE test_trigger_src_tbl DISABLE TRIGGER insert_trigger;  

--禁用当前表上所有触发器
postgres=# ALTER TABLE test_trigger_src_tbl DISABLE TRIGGER ALL;  

--删除触发器
postgres=# DROP TRIGGER insert_trigger ON test_trigger_src_tbl;
postgres=# DROP TRIGGER update_trigger ON test_trigger_src_tbl;
postgres=# DROP TRIGGER delete_trigger_renamed ON test_trigger_src_tbl;
support.huaweicloud.com/devg-v1-gaussdb/gaussdb_devg_0562.html