简体   繁体   English

在Oracle中INSERT之后选择最后一个ID

[英]SELECT the last ID after INSERT in Oracle

I'm aware of using RETURNING in an INSERT statement but need a way to either have it returned as a result of the INSERT statement (or enclosing transaction) or be able to retrieve that value using SELECT. 我知道在INSERT语句中使用RETURNING,但是需要一种方法使它作为INSERT语句(或封闭事务)的结果返回,或者能够使用SELECT检索该值。 Is there a way to do this? 有没有办法做到这一点? I cannot use DBMS_OUTPUT. 我不能使用DBMS_OUTPUT。 Thanks! 谢谢!

RETURNING clause is the easiest way to guarantee getting the value of the ID generated by an INSERT statement. RETURNING子句是确保获得由INSERT语句生成的ID的值的最简单方法。 Querying for max(id) is unreliable in a multi-user environment, especially if you're using RAC. 在多用户环境中,查询max(id)是不可靠的,尤其是在使用RAC的情况下。

If the ID is populated from a sequence you can get the current value of the sequence by running this in the same session as the INSERT: 如果从序列填充ID,则可以在与 INSERT 相同的会话中运行该序列,以获取序列的当前值:

 select your_sequence.currval from dual;

This means you need to know the name of the sequence, which isn't always obvious, even more so if you're using 12c Identity columns. 这意味着您需要知道序列的名称,这并不总是很明显,如果您使用的是12c Identity列,则更是如此。

Basically, if you want the ID use RETURNING. 基本上,如果要使用ID,请使用RETURNING。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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