select/display last inserted serial id in postgres

后端 未结 3 1186
被撕碎了的回忆
被撕碎了的回忆 2021-02-09 06:21

in sql server I do like this:

insert into foo(name) values(\'bob\')
select @@identity;

so I get a query/scalar result displayed

how to

3条回答
  •  一生所求
    2021-02-09 07:13

    A good way is using RETURNING id. Here is a short example using PL/pgSQL:

            DECLARE
            nivel1 RECORD;
            resultId BIGINT;
            BEGIN
              FOR nivel1 IN SELECT * FROM primary_table LOOP
                INSERT INTO second_table(id, field2, field3) VALUES (DEFAULT, "value2", "value3") RETURNING id INTO resultId;
                RAISE NOTICE 'Inserted id: %s', quote_literal(resultId);
              END LOOP;
            RETURN;
            END
    

    It works for me!

提交回复
热议问题