How can I insert the return of DELETE into INSERT in postgresql?

后端 未结 5 2185
闹比i
闹比i 2021-02-07 02:23

I am trying to delete a row from one table and insert it with some additional data into another. I know this can be done in two separate commands, one to delete and another to i

5条回答
  •  无人共我
    2021-02-07 03:00

    For all version of PostgreSQL, you can create a trigger function for deleting rows from a table and inserting them to another table. But it seems slower than bulk insert that is released in PostgreSQL 9.1. You just need to move the old data into the another table before it gets deleted. This is done with the OLD data type:

    CREATE FUNCTION moveDeleted() RETURNS trigger AS $$
        BEGIN
            INSERT INTO another_table VALUES(OLD.column1, OLD.column2,...);
            RETURN OLD;
        END;
    $$ LANGUAGE plpgsql;
    
    CREATE TRIGGER moveDeleted
    BEFORE DELETE ON table 
        FOR EACH ROW
            EXECUTE PROCEDURE moveDeleted();
    

    As above answer, after PostgreSQL 9.1 you can do this:

    WITH tmp AS (DELETE FROM table RETURNING column1, column2, ...)
        INSERT INTO another_table (column1, column2, ...) SELECT * FROM tmp;
    

提交回复
热议问题