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

歡迎補充


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM