PostgreSQL:设置两个彼此相等的时间戳。其中之一具有与之相关的触发器

时间:2019-01-09 21:32:08

标签: postgresql triggers

假设您有一个带有两个时间戳字段tablecreated的{​​{1}}。

updated具有如下触发器:

table

CREATE TRIGGER trig_table_on_update BEFORE UPDATE ON table FOR EACH ROW EXECUTE PROCEDURE func_table_on_update(); 的定义如下:

func_table_on_update

如何从另一个函数中设置CREATE OR REPLACE FUNCTION func_table_on_update() RETURNS trigger AS $$ BEGIN NEW.updated = current_timestamp; RETURN NEW; END; $$ ?问题是created := updated被设置为created,然后在提交时OLD.updatedOLD.updated覆盖。提交后,我需要保持两者之间的相等性,但不能始终设置为同一时间。

例如,

初始状态:

current_timestamp

更新后:

created            |updated            |
-------------------|-------------------|
2018-10-09 15:59:23|2018-11-12 16:00:22|

所需状态:

created            |updated            |
-------------------|-------------------|
2018-11-12 16:00:22|2019-01-09 16:00:22|

1 个答案:

答案 0 :(得分:1)

The trigger should be defined with the condition:

CREATE TRIGGER trig_table_on_update
BEFORE UPDATE ON my_table
FOR EACH ROW 
WHEN (NEW.created = OLD.created)
EXECUTE PROCEDURE func_table_on_update();

Also, add the statement in the trigger function:

    NEW.created = OLD.updated;

Now a transaction may look like this:

BEGIN;

UPDATE my_table
SET some_column = 'new value'
-- don't set created here!
WHERE id = 1;

SELECT *
FROM my_table;
-- here created <> updated

UPDATE my_table
SET created = updated
WHERE id = 1;
-- the trigger won't be fired

SELECT *
FROM my_table;
-- here created = updated

COMMIT;