sequence会产生一系列连续的不重复数字,但是这个序列很容易断号,尤其在有cache时,如果应用要求一定不能断号,那就不能使用sequence了。
建一序列zhaoss_test_seq:
SQL> create sequence zhaoss_test_seq
2 minvalue 1
3 maxvalue 100
4 start with 1
5 increment by 1
6 cache 20
7 order;
Sequence created
注意:刚刚创建的序列需要先用nextval来获取第一个初始值,否则会报如下错误:
SQL> select zhaoss_test_seq.currval from dual;
select zhaoss_test_seq.currval from dual
ORA-08002: 序列 ZHAOSS_TEST_SEQ.CURRVAL 尚未在此会话中定义
SQL> select zhaoss_test_seq.nextval from dual;
NEXTVAL
----------
1
清空内存看下结果:
SQL> alter system flush shared_pool;
System altered
SQL> select zhaoss_test_seq.currval from dual;
CURRVAL
----------
1
SQL> select zhaoss_test_seq.nextval from dual;
NEXTVAL
----------
21
从上面可以看出,清空内存后,当前值还是1,但是下一个值已经到了21,清空内存后丢失了20个连续的号码。
再清空一次内存看看:
SQL> alter system flush shared_pool;
System altered
SQL> select zhaoss_test_seq.currval from dual;
CURRVAL
----------
21
SQL> select zhaoss_test_seq.nextval from dual;
NEXTVAL
----------
41
通过上面实验可以看出:sequence中的cache会将后面要用的序列先缓存起来,以便下一次从内存中读出,从而加快速度。cache 20 就是缓存20个,而清空内存的动作导致序列不连续。
还有其他情况可以造成断号吗?
创建测试表
SQL> drop table t;
Table dropped
SQL> create table t(id number);
Table created
插入几行记录
SQL> insert into t values(zhaoss_test_seq.nextval);
1 row inserted
SQL> insert into t values(zhaoss_test_seq.nextval);
1 row inserted
SQL> insert into t values(zhaoss_test_seq.nextval);
1 row inserted
SQL> commit;
Commit complete
查看发现是连续的
SQL> select * from t;
ID
----------
42
43
44
SQL> insert into t values(zhaoss_test_seq.nextval);
1 row inserted
SQL> select * from t;
ID
----------
42
43
44
45
SQL> rollback;
Rollback complete
回滚后再插入一条记录发现已经不连续了。
SQL> insert into t values(zhaoss_test_seq.nextval);
1 row inserted
SQL> select * from t;
ID
----------
42
43
44
46
SQL>
总结:通过以上测试可以发现,sequence要保证连续是很困难的。如果采用cache形式,重启数据库或内存被清空都会导致缓存在cache中的连续号被清空,
就产生断号了。其实就算不设置为cache,一样会丢失,例如:回滚,执行失败等。因此要保证应用的该列是绝对要连续的,考虑sequence是很难保证的,
要考虑写代码来解决。
[@more@]
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/24496749/viewspace-1052097/
,如需转载,请注明出处,否则将追究法律责任。