简体   繁体   中英

How to save the last serial value in Postgres?

This is how I do in SQL Server:

insert into users(name, password) values('admin', '1');
declare @id int;
set @id = @@identity;
insert into usersroles values(@id, 1);
insert into usersroles values(@id, 2);

@@identity is in sql server the last inserted identity (serial)

How to do the same in Postgres?

The easiest way is to use the RETURNING clause for INSERT:

INSERT INTO users (name, password) VALUES ('admin', '1') RETURNING id;

That will return one row which contains the assigned id.

Another option is to use the currval function after you insert into the users table:

SELECT currval('users_id_seq');

From the intertubes:

  INSERT INTO Table1 (...)
    VALUES (...);

  GET DIAGNOSTICS res_oid = RESULT_OID;

  SELECT INTO ...
    FROM Table1 t
    WHERE t.oid = res_oid;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM