Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

sql - 如何在Oracle上使用AUTO_INCREMENT创建ID?(How to create id with AUTO_INCREMENT on Oracle?)

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

(直到并包括11g版,Oracle中似乎都没有AUTO_INCREMENT的概念。)

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

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

  ask by Sushan Ghimire translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is no such thing as "auto_increment" or "identity" columns in Oracle as of Oracle 11g .

(从Oracle 11g开始,Oracle中没有诸如“ auto_increment”或“ identity”列之类的东西。)

However, you can model it easily with a sequence and a trigger:

(但是,您可以使用序列和触发器轻松对其进行建模:)

Table definition:

(表定义:)

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;

Trigger definition:

(触发定义:)

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

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

UPDATE: (更新:)

IDENTITY column is now available on Oracle 12c:

(Oracle 12c上现在提供了IDENTITY列:)

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

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

(或指定起始值和增量值,也防止任何插入到身份列中( GENERATED ALWAYS )(同样,仅适用于Oracle 12c +))

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

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

(另外,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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...