如何在Oracle上使用AUTO_INCREMENT创建ID?
直到11g版本(包括11g),Oracle中似乎都没有AUTO_INCREMENT的概念。
如何在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));
以上是 如何在Oracle上使用AUTO_INCREMENT创建ID? 的全部内容, 来源链接: utcz.com/qa/414962.html