如何在 Oracle 上使用 AUTO_INCREMENT 创建 id?

2021-11-30 00:00:00 sql oracle auto-increment

在 Oracle 中似乎没有 AUTO_INCREMENT 的概念,直到并包括版本 11g.

It appears that there is no concept of AUTO_INCREMENT in Oracle, up until and including version 11g.

如何在 Oracle 11g 中创建一个行为类似于自动增量的列?

How can I create a column that behaves like auto increment in Oracle 11g?

推荐答案

Oracle 中没有auto_increment"或identity"列之类的东西从 Oracle 11g 开始.但是,您可以使用序列和触发器轻松对其进行建模:

There is no such thing as "auto_increment" or "identity" columns in Oracle as of Oracle 11g. However, you can model it easily with a sequence and a trigger:

表定义:

CREATE TABLE departments (
  ID           NUMBER(10)    NOT NULL,
  DESCRIPTION  VARCHAR2(50)  NOT NULL);

ALTER TABLE departments ADD (
  CONSTRAINT dept_pk PRIMARY KEY (ID));

CREATE SEQUENCE dept_seq START WITH 1;

触发器定义:

CREATE OR REPLACE TRIGGER dept_bir 
BEFORE INSERT ON departments 
FOR EACH ROW

BEGIN
  SELECT dept_seq.NEXTVAL
  INTO   :new.id
  FROM   dual;
END;
/

更新:

IDENTITY 列是现在可在 Oracle 12c 上使用:

UPDATE:

IDENTITY column is now available on Oracle 12c:

create table t1 (
    c1 NUMBER GENERATED by default on null as IDENTITY,
    c2 VARCHAR2(10)
    );

或指定起始值和增量值,同时防止对标识列进行任何插入(GENERATED ALWAYS)(同样,仅适用于 Oracle 12c+)

or specify starting and increment values, also preventing any insert into the identity column (GENERATED ALWAYS) (again, Oracle 12c+ only)

create table t1 (
    c1 NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1),
    c2 VARCHAR2(10)
    );

或者,Oracle 12 还允许使用序列作为默认值:

Alternatively, Oracle 12 also allows to use a sequence as a default value:

CREATE SEQUENCE dept_seq START WITH 1;

CREATE TABLE departments (
  ID           NUMBER(10)    DEFAULT dept_seq.nextval NOT NULL,
  DESCRIPTION  VARCHAR2(50)  NOT NULL);

ALTER TABLE departments ADD (
  CONSTRAINT dept_pk PRIMARY KEY (ID));

相关文章