首页 > 代码库 > Oracle12c:支持通过创建identity columen来实现创建自增列

Oracle12c:支持通过创建identity columen来实现创建自增列

oracle12c之前如果需要创建自增列必须要通过sequence+trigger来实现。但是oracle12c已经可以像mysql,sqlserver一样通过identity column来设置自增列了。

 1 Connected to Oracle Database 12c Enterprise Edition Release 12.1.0.1.0  2 Connected as My@TEST 3  4 SQL>  5 SQL> create table tab_test2 6   2  ( 7   3      id number(38) generated as identity (start with 1 increment by 1), 8   4      name varchar2(30), 9   5      constraint PK_tab_test2 primary key (id)10   6  );11 Table created12 13 SQL> insert into tab_test2(name)values(hello);14 1 row inserted15 16 SQL> select * from tab_test2;17                                      ID NAME18 --------------------------------------- ------------------------------19                                       1 hello20 21 SQL> insert into tab_test2(name)values(hello2);22 1 row inserted23 24 SQL> insert into tab_test2(name)values(hello3);25 1 row inserted26 27 SQL> select * from tab_test2;28                                      ID NAME29 --------------------------------------- ------------------------------30                                       1 hello31                                       2 hello232                                       3 hello333 34 SQL> drop table tab_test2;35 Table dropped

当然也支持12c之前的版本所采用的方案:sequence+trigger的方案

 1 SQL>  2 SQL> create table t_test (id number,name varchar2(100)); 3 Table created 4 SQL> create sequence t_test_sequence 5   2  increment by 1 6   3  minvalue 1 7   4  nomaxvalue 8   5  start with 1 9   6  cache 2010   7  order;11 Sequence created12 SQL> create or replace trigger t_test_id13   2  before insert on t_test14   3  for each row15   4  begin16   5  select t_test_sequence.nextval into :new.id from dual;17   6  end;18   7  /19 Trigger created20 SQL> insert into t_test(name) values(hello1);21 1 row inserted22 SQL> insert into t_test(name) values(hello2);23 1 row inserted24 SQL> insert into t_test(name) values(hello3);25 1 row inserted26 27 SQL> select * from t_test;28         ID NAME29 ---------- --------------------------------------------------------------------------------30          1 hello131          2 hello232          3 hello333 34 SQL> drop table t_test;35 Table dropped36 37 SQL> 

 

查阅文档:

http://www.xifenfei.com/2015/03/oracle-12c-%E6%96%B0%E7%89%B9%E6%80%A7identity-columns-%E5%AE%9E%E7%8E%B0oracle%E8%87%AA%E5%A2%9E%E9%95%BF%E5%88%97%E5%8A%9F%E8%83%BD.html

Oracle12c:支持通过创建identity columen来实现创建自增列