如何将自动增量添加到 Oracle 中现有的 table

How add autoincrement to existing table in Oracle

是否有任何方法可以在 Oracle 12c 中现有 table 的主键中添加自动增量。可能与 ALTER TABLE 函数或 smth,我的意思是没有触发器和序列。

据我所知,您可以 not "modify" 现有主键列到 "real" 标识列中。

如果你想这样做,你必须删除当前的主键列,然后更改 table 并添加一个新的 identity 列。


解决方法是使用序列(或触发器),但是 - 您说过您不想这样做。无论如何,如果您决定使用它:

SQL> create table test
  2   (id   number constraint pk_test primary key,
  3    name varchar2(10));

Table created.

SQL> insert into test values (1, 'LF');

1 row created.

SQL> create sequence seq_test start with 2;

Sequence created.

SQL> alter table test modify id default seq_test.nextval;

Table altered.

SQL> insert into test (name) values ('BF');

1 row created.

SQL> select * from test;

        ID NAME
---------- ----------
         1 LF
         2 BF

SQL>

或者,删除当前主键列(请注意,如果涉及外键,这将不会很容易):

SQL> alter table test drop column id;

Table altered.

SQL> alter table test add id number generated always as identity;

Table altered.

SQL> select * From test;

NAME               ID
---------- ----------
LF                  1
BF                  2

SQL> insert into test (name) values ('test');

1 row created.

SQL> select * From test;

NAME               ID
---------- ----------
LF                  1
BF                  2
test                3

SQL>