How do I automatically update a timestamp in PostgreSQL

后端 未结 4 573
执念已碎
执念已碎 2020-12-07 08:15

I want the code to be able to automatically update the time stamp when a new row is inserted as I can do in MySQL using CURRENT_TIMESTAMP.

How will I be able to achi

4条回答
  •  天命终不由人
    2020-12-07 08:55

    You'll need to write an insert trigger, and possible an update trigger if you want it to change when the record is changed. This article explains it quite nicely:

    http://www.revsys.com/blog/2006/aug/04/automatically-updating-a-timestamp-column-in-postgresql/

    CREATE OR REPLACE FUNCTION update_modified_column()   
    RETURNS TRIGGER AS $$
    BEGIN
        NEW.modified = now();
        RETURN NEW;   
    END;
    $$ language 'plpgsql';
    

    Apply the trigger like this:

    CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON customer FOR EACH ROW EXECUTE PROCEDURE  update_modified_column();
    

提交回复
热议问题