我用自动增长序列来生成表的主键
1、建立自动增长序列
create sequence test_seq
minvalue 1 maxvalue 99999999999999
increment by 1
start with 1;
2、创建触发器
create or replace trigger test_trigger
before insert on test
for each row
begin 
select test_seq.nextval into :new.data_id from dual;
end test_trigger;
/
这样利用触发器与自动增长序列建立了数据库的自动生成主键
但是,我不停的运行数据库,如果连续往数据库里添加数据,则ID是连续的
但是如果是上下午,或者分别两天的时间往数据库里添加,就会出现ID不连续的问题
例如:
第一天添加的数据的ID到103
第二天在添加数据时ID就为121了
这是为什么?

解决方案 »

  1.   

    你不连续操作这段时间内,可能你用别的程序调用了test_seq.nextval
    或者别人调用了test_seq.nextval,导致了test_seq的增长
      

  2.   

    NOCACHE 
        specifies that values of the sequence are not preallocated.     If you omit both the CACHE parameter and the NOCACHE option, Oracle 
        caches 20 sequence numbers by default.  However, if you are using 
        Oracle with the Parallel Server option in parallel mode and you 
        specify the ORDER option, sequence values are never cached, 
        regardless of whether you specify the CACHE parameter or the NOCACHE     option. 
      

  3.   

    序列实现唯一性 即使没有其它程序调用序列 可能在操作程序执行失败时已经调用了test_seq.nextval 序列也不会连续了 
      

  4.   

    几种情况:1) 1楼所说的
    2) 你做的rollback事务,但是sequence不会再变小的
    3) 你创建的sequence没有批暄nocache,如4楼,你得加上nocache,否则可能造成缓存的20个数字不连续了
      

  5.   

    把你的sequence改成:create sequence test_seq 
    minvalue 1 maxvalue 99999999999999 
    increment by 1 
    start with 1
    nocache
      

  6.   

    你要确保ID是连续并且唯一的
    只有用
    select max(id) from a fro update
      

  7.   

    select max(id) from a fro update,这个用的是悲观锁,可以尝试用乐观锁试试
      

  8.   

    cache会把sequence缓存在lb cache中,在lb cache中对对象的age out是基于lru算法的,如果cache 20,会把这个序列每次取的时候取出来20个,然后再在lb cache中一个一个用,但是如果在用完这20个之前,这个序列被aged out了,那么没用的那些数就丢掉了,而下次再去从dd取出sequence的时候就会去取上次那20个+1的号为开始,再来20个。这就是产生断号的原因。所以建议你不用cache
      

  9.   

    sequence很难做到保证取到的数据连续,
    nocache+单用户,并在不出现事务失败或机器故障等意外原因,才可能连续,总之比较难.
      

  10.   

    你要确保ID是连续并且唯一的 
    只有用 
    select max(id) from a fro update
    你不连续操作这段时间内,可能你用别的程序调用了test_seq.nextval 
    或者别人调用了test_seq.nextval,导致了test_seq的增长