触发器——插入或者更新会触发时间戳更新

235 阅读1分钟
  1. 数据库中创建表

     DROP TABLE IF EXISTS es_table;
     CREATE TABLE es_table
     (
         id integer NOT NULL,
         province character varying(32) COLLATE pg_catalog."default" NOT NULL,
         modification_time timestamp without time zone NOT NULL DEFAULT now(),
         CONSTRAINT es_table_pkey PRIMARY KEY (id)
     )
    
  2. 数据库中创建函数

     create or replace function upd_timestamp() returns trigger as
     $$
     begin
         new.modification_time = current_timestamp;
         return new;
     end
     $$
     language plpgsql;	
     
    
  3. 数据库中创建触发器

     create trigger updated_date after update or insert on es_table for each row execute procedure upd_timestamp();
     
    
  4. 数据库中插入数据

     INSERT INTO es_table (id, province) VALUES (110, 'wys');
     
    
  5. 修改数据

     update es_table set province='wwwww' where province='wys'
     
    
  6. 通过以下语句查询数据,发现 modification_time 字段值发生了变化

     select * from es_table