zoukankan      html  css  js  c++  java
  • postgresql获取表最后更新时间(通过触发器将时间写入另外一张表)

    通过触发器方式获取表最后更新时间,并将时间信息写入到另外一张表

    一、创建测试表和表记录更新时间表

    复制代码
    CREATE TABLE weather(
    city varchar(80),
    temp_lo int,  --最低温度
    temp_hi int,  --最高温度
    prcp real,     --湿度
    date date
    );
    复制代码
    复制代码
    CREATE TABLE t_record_change(
    table_name varchar(32) primary key,
    last_update_time timestamp(6) with time zone,
    trans_id varchar(32),
    commited numeric(1,0)
    );
    复制代码

    二、创建触发器函数

    复制代码
    --创建触发器函数
    create or replace function f_update_change_log() returns trigger as $$
    begin
        insert into t_record_change(table_name,last_update_time,trans_id,commited) values(TG_TABLE_NAME,current_timestamp,(select txid_current()),1)
            on conflict(table_name)
        do update set last_update_time = current_timestamp,trans_id = (select txid_current()),commited = 1;
        return null;
    end;
    $$ language plpgsql;
    复制代码

    三、创建触发器

    --创建触发器
    drop trigger if exists x_weather_u on weather;
    create trigger x_weather_u after insert or update or delete on weather
    for each statement execute procedure f_update_change_log();

    四、测试

    在sql窗口中分别执行以下sql语句,并到t_record_change表中查看时间是否更新

    insert into weather values('nanjing',20,40,0.28,'2018-06-27');
    update weather set temp_lo = 15 where city = 'nanjing';
    delete from weather where city = 'nanjing';

     
     
    posted @ 2018-07-05 15:55 Luis Yang 阅读(1165) 评论(0) 编辑 
  • 相关阅读:
    LeetCode: Tags-[Array], Difficulty-[Medium]
    J2SE 常用方法
    LeetCode: Tags-[Array], Difficulty-[Easy]
    Java Code Style 记录
    LintCode 1-30;
    Android在线程中发送GET和POST请求 在主线程更新UI
    Android中intent启动Activity中intent.setFlags()的作用
    源码备份 listview
    android数据库操作
    android 验证二
  • 原文地址:https://www.cnblogs.com/telwanggs/p/11021525.html
Copyright © 2011-2022 走看看