[英]How to save the last serial value in Postgres?
This is how I do in SQL Server: 这是我在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) @@identity
是sql server中最后插入的身份(序列)
How to do the same in Postgres? 在Postgres中该怎么做?
The easiest way is to use the RETURNING clause for INSERT: 最简单的方法是对INSERT使用RETURNING子句:
INSERT INTO users (name, password) VALUES ('admin', '1') RETURNING id;
That will return one row which contains the assigned id. 这将返回一行,其中包含已分配的ID。
Another option is to use the currval
function after you insert into the users table: 另一种选择是在插入用户表后使用
currval
函数:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.