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

如何在Oracle 11g中创建一个行为像自动递增的列?


当前回答

FUNCTION UNIQUE2(
 seq IN NUMBER
) RETURN VARCHAR2
AS
 i NUMBER := seq;
 s VARCHAR2(9);
 r NUMBER(2,0);
BEGIN
  WHILE i > 0 LOOP
    r := MOD( i, 36 );
    i := ( i - r ) / 36;
    IF ( r < 10 ) THEN
      s := TO_CHAR(r) || s;
    ELSE
      s := CHR( 55 + r ) || s;
    END IF;
  END LOOP;
  RETURN 'ID'||LPAD( s, 14, '0' );
END;

其他回答

查询如何在oracle中创建自动增量。在下面的查询中,每当插入新行时,列值将自动递增

CREATE TABLE table1(
id RAW(16) NOT NULL ENABLE,
incrmnt NUMBER(10,0) GENERATED ALWAYS AS IDENTITY
MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 1 NOORDER NOCYCLE NOT NULL ENABLE,
CONSTRAINT PK_table1 PRIMARY KEY (id) ENABLE);

假设您指的是类似SQL Server标识列的列?

在Oracle中,您可以使用SEQUENCE来实现相同的功能。我看看能不能找到一个好的链接,然后贴在这里。

更新:看起来你自己找到了。这里是链接: http://www.techonthenet.com/oracle/sequences.php

Oracle数据库12c引入了Identity,一个自动增量(系统生成)列。 在以前的数据库版本中(直到11g),您通常通过创建Sequence和Trigger来实现Identity。 从12c开始,您可以创建自己的Table并定义必须作为Identity生成的列。

这里有三种口味:

数字。简单递增的数值,例如1,2,3,.... GUID。全局通用标识符,作为RAW数据类型。 GUID(字符串)。与上面相同,但作为字符串,在某些语言中可能更容易处理。

X是单位列。在每个示例中,用表名替换FOO。

-- numerical identity, e.g. 1,2,3...
create table FOO (
    x number primary key
);
create sequence  FOO_seq;

create or replace trigger FOO_trg
before insert on FOO
for each row
begin
  select FOO_seq.nextval into :new.x from dual;
end;
/

-- GUID identity, e.g. 7CFF0C304187716EE040488AA1F9749A
-- use the commented out lines if you prefer RAW over VARCHAR2.
create table FOO (
    x varchar(32) primary key        -- string version
    -- x raw(32) primary key         -- raw version
);

create or replace trigger FOO_trg
before insert on FOO
for each row
begin
  select cast(sys_guid() as varchar2(32)) into :new.x from dual;  -- string version
  -- select sys_guid() into :new.x from dual;                     -- raw version
end;
/

更新:

Oracle 12c引入了两个不依赖触发器的变体:

create table mytable(id number default mysequence.nextval);
create table mytable(id number generated as identity);

第一个是传统的序列;第二个在内部管理值。

oracle在12c中有序列和标识列

http://www.oracle-base.com/articles/12c/identity-columns-in-oracle-12cr1.php#identity-columns

我发现了这个,但不确定rdb7是什么 http://www.oracle.com/technetwork/products/rdb/0307-identity-columns-128126.pdf