在Oracle中插入后返回identity列的值

时间:2015-02-12 07:54:48

标签: sql oracle identity-column oracle12c sql-returning

如何在插入后在Oracle 12c中返回标识列(id)的值?似乎大多数方法都使用序列来取回插入项目的id。

1 个答案:

答案 0 :(得分:9)

只需使用 RETURNING 子句。

例如 -

RETURNING identity_id INTO variable_id;

测试用例 -

SQL> set serveroutput on
SQL> CREATE TABLE t
  2    (ID NUMBER GENERATED ALWAYS AS IDENTITY, text VARCHAR2(50)
  3    );

Table created.

SQL>
SQL> DECLARE
  2    var_id NUMBER;
  3  BEGIN
  4    INSERT INTO t
  5      (text
  6      ) VALUES
  7      ('test'
  8      ) RETURNING ID INTO var_id;
  9    DBMS_OUTPUT.PUT_LINE('ID returned is = '||var_id);
 10  END;
 11  /
ID returned is = 1

PL/SQL procedure successfully completed.

SQL>

SQL> select * from t;

        ID TEXT
---------- --------------------------------------------
         1 test

SQL>