Postgres UPSERT (INSERT or UPDATE) only if value is different

前端 未结 6 1561
你的背包
你的背包 2021-02-05 17:26

I\'m updating a Postgres 8.4 database (from C# code) and the basic task is simple enough: either UPDATE an existing row or INSERT a new one if one doesn\'t exist yet. Normally I

6条回答
  •  执笔经年
    2021-02-05 17:35

    Take a look at a BEFORE UPDATE trigger to check and set the correct values:

    CREATE OR REPLACE FUNCTION my_trigger() RETURNS TRIGGER LANGUAGE plpgsql AS
    $$
    BEGIN
        IF OLD.content = NEW.content THEN
            NEW.updated_time= OLD.updated_time; -- use the old value, not a new one.
        ELSE
            NEW.updated_time= NOW();
        END IF;
        RETURN NEW;
    END;
    $$;
    

    Now you don't even have to mention the field updated_time in your UPDATE query, it will be handled by the trigger.

    http://www.postgresql.org/docs/current/interactive/plpgsql-trigger.html

提交回复
热议问题