【问题标题】:How add autoincrement to existing table in OracleOracle中如何将自动增量添加到现有表中
【发布时间】:2020-04-29 22:06:19
【问题描述】:

有没有办法在 Oracle 12c 中已经存在的表中添加自动增量到主键。可能带有 ALTER TABLE 函数或其他东西,我的意思是没有触发器和序列。

【问题讨论】:

    标签: oracle oracle12c auto-increment


    【解决方案1】:

    据我所知,您可以将现有主键列“修改”为“真实”标识列。

    如果你想这样做,你必须删除当前的主键列,然后改变表并添加一个新的 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>
    

    【讨论】:

      猜你喜欢
      • 2013-01-23
      • 2021-08-08
      • 1970-01-01
      • 2015-06-05
      • 2016-05-29
      • 2019-01-18
      • 2012-07-12
      相关资源
      最近更新 更多