直到11g版本(包括11g)为止,Oracle中似乎都没有AUTO_INCREMENT的概念。
如何在Oracle 11g中创建行为类似于自动增量的列?
从Oracle 11g开始,Oracle中 没有诸如“ auto_increment”或“ identity”列之类的东西。但是,您可以使用序列和触发器轻松对其进行建模:
表定义:
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上可用:
IDENTITY
create table t1 ( c1 NUMBER GENERATED by default on null as IDENTITY, c2 VARCHAR2(10) );
或指定起始值和增量值,还防止任何插入到标识列(GENERATED ALWAYS)中(同样,仅适用于Oracle 12c +)
GENERATED ALWAYS
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));