views:

25

answers:

2

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?

+4  A: 

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');
Lukáš Lalinský
+1  A: 

From the intertubes:

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

  GET DIAGNOSTICS res_oid = RESULT_OID;

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