postgresql 在 postgres 中选择/显示最后插入的序列号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3687698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
select/display last inserted serial id in postgres
提问by Omu
in sql server I do like this:
在 sql server 中,我喜欢这样:
insert into foo(name) values('bob')
select @@identity;
so I get a query/scalar result displayed
所以我得到一个查询/标量结果显示
how to this with postgres ?
如何用 postgres 做到这一点?
回答by Frank Heikens
Get a specific sequence:
获取特定序列:
SELECT currval('name_of_your_sequence');
Get the last value from the last sequence used:
从最后使用的序列中获取最后一个值:
SELECT lastval();
Check the manual as well: http://www.postgresql.org/docs/current/static/functions-sequence.html
也检查手册:http: //www.postgresql.org/docs/current/static/functions-sequence.html
Edit: You could also use RETURNING in your INSERT:
编辑:您也可以在 INSERT 中使用 RETURNING:
INSERT INTO foo(id, name) VALUES(DEFAULT, 'bob') RETURNING id;
回答by hermeslm
A good way is using RETURNING id. Here is a short example using PL/pgSQL:
一个好方法是使用 RETURNING id。这是一个使用 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!
这个对我有用!
回答by SQLMenace
It would be
这将是
GET DIAGNOSTICS YourParam = RESULT_OID;
获取诊断信息 YourParam = RESULT_OID;
See here http://www.postgresql.org/docs/8.2/static/plpgsql-statements.htmlscroll down to 37.6.6. Obtaining the Result Status
请参阅此处http://www.postgresql.org/docs/8.2/static/plpgsql-statements.html向下滚动到 37.6.6。获取结果状态
asker edit:I tried this:
提问者编辑:我试过这个:
create or replace function aaa() returns int as $$
declare
a int;
begin
insert into oameni values(default, 'aaa');
get diagnostics a = result_oid;
return a;
end;
$$ language plpgsql;
it always returns 0, you know what's wrong here?
它总是返回 0,你知道这里有什么问题吗?