Insert, on duplicate update in PostgreSQL?

前端 未结 16 2777
别那么骄傲
别那么骄傲 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:30

    I was looking for the same thing when I came here, but the lack of a generic "upsert" function botherd me a bit so I thought you could just pass the update and insert sql as arguments on that function form the manual

    that would look like this:

    CREATE FUNCTION upsert (sql_update TEXT, sql_insert TEXT)
        RETURNS VOID
        LANGUAGE plpgsql
    AS $$
    BEGIN
        LOOP
            -- first try to update
            EXECUTE sql_update;
            -- check if the row is found
            IF FOUND THEN
                RETURN;
            END IF;
            -- not found so insert the row
            BEGIN
                EXECUTE sql_insert;
                RETURN;
                EXCEPTION WHEN unique_violation THEN
                    -- do nothing and loop
            END;
        END LOOP;
    END;
    $$;
    

    and perhaps to do what you initially wanted to do, batch "upsert", you could use Tcl to split the sql_update and loop the individual updates, the preformance hit will be very small see http://archives.postgresql.org/pgsql-performance/2006-04/msg00557.php

    the highest cost is executing the query from your code, on the database side the execution cost is much smaller

提交回复
热议问题