暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 关于比列低的序列的问题

ASKTOM 2021-01-18
364

问题描述

嗨,

我有一个序列名称s1以1开头,以1递增,以999结尾。

我将这些序列值插入到一个表名 'e' 中。E表包含eno (pk) 列。

插入到e值中 (s1.nextval);

我插入了9行。序列当前值为9,并且后端已插入10。我试着

插入到e值中 (s1.nextval);

然后它会出现pk违反错误。在这种情况下,我想插入11代替10

专家解答

在11g中没有很好的解决方案。您必须通过调用sequence.nextval或删除/重新创建序列来手动消耗高达当前PK max的序列值。

从12c可以定义标识列。这些使用封面下的序列。您可以使用alter table将它们提升到列中的当前最高值:

create table t (
  c1 int 
    generated by default as identity
    primary key
);

begin
  for i in 1 .. 9 loop
    insert into t values ( default );
  end loop;
  
  insert into t values ( 10 );
  insert into t values ( 20 );
  commit;
end;
/

insert into t values ( default );

ORA-00001: unique constraint (CHRIS.SYS_C0024541) violated

alter table t
  modify c1 
  generated by default as identity (
      start with limit value 
  );

var id number;
insert into t values ( default )
  returning c1 into :id;
  
print :id

        ID
----------
        21


或者从18c可以使用restart子句来设置nextval:

create sequence s;

select s.nextval from dual;

NEXTVAL   
         1 

alter sequence s
  restart start with 99;
  
select s.nextval from dual;

drop sequence s;

NEXTVAL   
        99 

文章转载自ASKTOM,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论