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 created 12 13 SQL> insert into tab_test2(name)values('hello'); 14 1 row inserted 15 16 SQL> select * from tab_test2; 17 ID NAME 18 --------------------------------------- ------------------------------ 19 1 hello 20 21 SQL> insert into tab_test2(name)values('hello2'); 22 1 row inserted 23 24 SQL> insert into tab_test2(name)values('hello3'); 25 1 row inserted 26 27 SQL> select * from tab_test2; 28 ID NAME 29 --------------------------------------- ------------------------------ 30 1 hello 31 2 hello2 32 3 hello3 33 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 20 10 7 order; 11 Sequence created 12 SQL> create or replace trigger t_test_id 13 2 before insert on t_test 14 3 for each row 15 4 begin 16 5 select t_test_sequence.nextval into :new.id from dual; 17 6 end; 18 7 / 19 Trigger created 20 SQL> insert into t_test(name) values('hello1'); 21 1 row inserted 22 SQL> insert into t_test(name) values('hello2'); 23 1 row inserted 24 SQL> insert into t_test(name) values('hello3'); 25 1 row inserted 26 27 SQL> select * from t_test; 28 ID NAME 29 ---------- -------------------------------------------------------------------------------- 30 1 hello1 31 2 hello2 32 3 hello3 33 34 SQL> drop table t_test; 35 Table dropped 36 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