问题

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

如何在Oracle 11g中创建类似自动增量的列?

  最佳答案

Oracle 11g中没有“自动增量”或“身份”列.但是,您可以使用序列和触发器轻松建模它:

表定义:

 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:

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

或者指定启动和增量值,也防止任何插入身份列(GENERATED ALWAYS)(再次,Oracle 12c)

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

或者,Oracle 12也允许将序列作为默认值:

 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));
 

  相同标签的其他问题

sqloracleauto-increment