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

后端 未结 5 2193
闹比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

    Before PostgreSQL 9.1 you can create a volatile function like this (untested):

    create function move_from_a_to_b(_id integer, _num integer)
    returns void language plpgsql volatile as
    $$
      declare
        _one integer;
        _two integer;
      begin
        delete from a where id = _id returning one, two into strict _one, _two;
        insert into b (one,two,num) values (_one, _two, _num);
      end;
    $$
    

    And then just use select move_from_a_to_b(1, 5). A function has the advantage over two statements that it will always run in single transaction — there's no need to explicitly start and commit transaction in client code.

提交回复
热议问题