【问题标题】:How to create stored procedure to save history of specific column before update in postgres如何在 postgres 更新之前创建存储过程以保存特定列的历史记录
【发布时间】:2021-01-21 03:40:02
【问题描述】:

基本上,我只想在更新之前获取特定列的旧值并将其存储在另一个表中。我想使用 Postgres 中的存储过程来完成此操作。

transaction_table

tid (primary)
status_id (integer)

history_table

hid (primary)
tid (integer)
old_value (integer)
new_value (integer)
date (timestamp)

status_id 中的任何更改都将存储在history_table 中。这可能吗?

【问题讨论】:

标签: postgresql stored-procedures triggers


【解决方案1】:

执行此操作的规范方法是使用触发器:

CREATE FUNCTION trans_hist() RETURNS trigger
   LANGUAGE plpgsql AS
$$BEGIN
   INSERT INTO history_table (tid, old_value, new_value, date)
   VALUES (NEW.tid, OLD.status_id, NEW.status_id, chrrent_timestamp);

   RETURN NEW;
END;$$;

CREATE TRIGGER trans_hist AFTER UPDATE ON transaction_table
   FOR EACH ROW EXECUTE PROCEDURE trans_hist();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2017-02-24
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    相关资源
    最近更新 更多