How to save the last serial value in Postgres?
This is how I do in SQL Serve开发者_高级运维r:
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;
精彩评论