Insert, on duplicate update in PostgreSQL?

前端 未结 16 2308
别那么骄傲
别那么骄傲 2020-11-21 04:52

Several months ago I learned from an answer on Stack Overflow how to perform multiple updates at once in MySQL using the following syntax:

INSERT INTO table          


        
16条回答
  •  春和景丽
    2020-11-21 05:32

    I custom "upsert" function above, if you want to INSERT AND REPLACE :

    `

     CREATE OR REPLACE FUNCTION upsert(sql_insert text, sql_update text)
    
     RETURNS void AS
     $BODY$
     BEGIN
        -- first try to insert and after to update. Note : insert has pk and update not...
    
        EXECUTE sql_insert;
        RETURN;
        EXCEPTION WHEN unique_violation THEN
        EXECUTE sql_update; 
        IF FOUND THEN 
            RETURN; 
        END IF;
     END;
     $BODY$
     LANGUAGE plpgsql VOLATILE
     COST 100;
     ALTER FUNCTION upsert(text, text)
     OWNER TO postgres;`
    

    And after to execute, do something like this :

    SELECT upsert($$INSERT INTO ...$$,$$UPDATE... $$)
    

    Is important to put double dollar-comma to avoid compiler errors

    • check the speed...

提交回复
热议问题