INSERT事件触发器函数

最近更新时间: 2024-06-12 15:06:00

函数功能实现字段值t_trigger.nc值重写。

postgres=# CREATE TABLE t_trigger
postgres-# (
postgres(#     id integer NOT NULL,
postgres(#     nc text NOT NULL
postgres(# );
CREATE TABLE
postgres=# CREATE OR REPLACE FUNCTION t_trigger_insert_trigger_func() RETURNS trigger AS 
postgres-# $$
postgres$# BEGIN
postgres$#     IF NEW.nc = '' THEN    
postgres$#         NEW.nc = 'TDSQLPG_' || random()::text;
postgres$#     END IF;
postgres$#     RETURN NEW;
postgres$# END;
postgres$# $$ 
postgres-# LANGUAGE plpgsql;
CREATE FUNCTION
postgres=# CREATE TRIGGER t_trigger_insert_trigger BEFORE INSERT ON t_trigger FOR EACH ROW EXECUTE PROCEDURE t_trigger_insert_trigger_func();
CREATE TRIGGER
postgres=# INSERT INTO t_trigger values(1,'');
INSERT 0 1
postgres=# SELECT * FROM t_trigger ;
 id |           nc            
----+-------------------------
  1 | TDSQLPG_0.426093454472721
(1 row)

注意:

使用BEFORE,不能使用AFTER,否则重写失效。