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

How to create id with AUTO_INCREMENT on Oracle?(如何在 Oracle 上使用 AUTO_INCREMENT 创建 id?)
本文介绍了如何在 Oracle 上使用 AUTO_INCREMENT 创建 id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于如何在 Oracle 上使用 AUTO_INCREMENT 创建 id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)