1. 测试环境:
SQL> select * from v$version ;
BANNER
--------------------------------------------------------------------------------
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
PL/SQL Release 11.2.0.1.0 - Production
CORE 11.2.0.1.0 Production
TNS for Linux: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production
SQL> create sequence test_seq1;
Sequence created.
2.开始测试:
SQL>select DBMS_METADATA.get_ddl ('SEQUENCE','TEST_SEQ1') from dual;
DBMS_METADATA.GET_DDL('SEQUENCE','TEST_SEQ1')
----------------------------------------------------------------------------------------------------------------------------------------------
CREATE SEQUENCE "SCOTT"."TEST_SEQ1" MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE
--可以发现,这样建立的sequence,缺省start=1,cache=20,NOORDER NOCYCLE,步进=1.
SQL> select test_seq1.nextval from dual ;
NEXTVAL
----------
1
SQL> select test_seq1.currval from dual ;
CURRVAL
----------
1
--现在建立一张表,插入数据看看。
create table test_seq(id number,name varchar2(10));
SQL> insert into test_seq values (test_seq1.nextval,'test');
1 row created.
SQL> commit ;
Commit complete.
SQL> select * from test_seq;
ID NAME
---------- ----------
3 test
--可以发现跳过了2,直接是3.
--BTW,今天我才知道问题的原因。实际上在以前的一些学习中,我已经遇到这个问题,我自己并没有在钻研下去,看来这个就是高手与低手之间的区别。
--主要是段延迟建立的特性引起的。
http://mwidlake.wordpress.com/2011/11/17/skipped-initial-sequence-value-on-oracle-11-2/
http://orawin.info/blog/2010/04/25/new-features-new-defaults-new-side-effects/
{update, see the post comments and this post by Niall – this is a side effect of delayed segment creation – the first insert
silently fails, but gets the sequence, and is repeated behind the scenes once the segment is there. It is fixed in 11.2.0.3, my db
is at 11.2.0.1 as I got sick of the download of the latest version failing on my poor broadband connection and got it off a mate –
turns out it is not the latest version.}
3.建立一个没有段延迟的表:
SQL> drop table test_seq purge;
Table dropped.
SQL> drop sequence test_seq1;
Sequence dropped.
SQL> create sequence test_seq1;
Sequence created.
SQL> create table test_seq(id number,name varchar2(10)) SEGMENT CREATION IMMEDIATE;
Table created.
SQL> insert into test_seq values(test_seq1.nextval,'test');
1 row created.
SQL> commit ;
Commit complete.
SQL> select * from test_seq;
ID NAME
---------- ----------
1 test
--可以发现插入的序号从1开始。