随笔 - 272  文章 - 0  评论 - 283  阅读 - 142万

PostgreSQL之时间戳自动更新

操作系统 :CentOS7.3.1611_x64

PostgreSQL版本 :9.6

问题描述

PostgreSQL执行Insert语句时,自动填入时间的功能可以在创建表时实现,但更新表时时间戳不会自动自动更新。

在mysql中可以在创建表时定义自动更新字段,比如 :

create table ab (
  id int,
  changetimestamp timestamp
    NOT NULL
    default CURRENT_TIMESTAMP
    on update CURRENT_TIMESTAMP
);

那PostgreSQL中怎么操作呢?

解决方案

通过触发器实现,具体如下:

复制代码
create or replace function upd_timestamp() returns trigger as
$$
begin
    new.modified = current_timestamp;
    return new;
end
$$
language plpgsql;

drop table if exists ts;
create table ts (
    id      bigserial  primary key,
    tradeid integer ,
    email varchar(50),
    num integer,
    modified timestamp default current_timestamp
);
create trigger t_name before update on ts for each row execute procedure upd_timestamp();
复制代码

测试代码:

复制代码
insert into ts (tradeid,email,num) values (1223,'mike_zhang@live.com',1);
update ts set email='Mike_Zhang@live' where tradeid = 1223 ;

create unique index ts_tradeid_idx on ts(tradeid);
insert into ts(tradeid,email,num) values (1223,'Mike_Zhang@live.com',2) on conflict(tradeid) do update
set email = excluded.email,num=excluded.num;

select * from ts;
-- delete from ts;
复制代码

注意: 以上代码在pgAdmin 4 v1客户端测试通过,使用DbVisualizer工具执行上述代码会报错。

好,就这些了,希望对你有帮助。

本文github地址:

https://github.com/mike-zhang/mikeBlogEssays/blob/master/2017/20171013_PostgreSQL之时间戳自动更新.rst

欢迎补充

posted on   Mike_Zhang  阅读(12489)  评论(1编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2012-10-18 在成员函数中使用STL的find_if函数
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示