【问题标题】:Oracle SQL | Auto incremented ID is not incremented when an id is provided甲骨文 SQL |提供 id 时,自动递增的 ID 不会递增
【发布时间】:2021-04-25 05:55:29
【问题描述】:

我有以下递增的 id:

create table PATIENT (
   PATIENTID            INTEGER             
      generated by default on null as identity ( start with 1 nocycle order)  not null
);

我注意到,当我提供一个 id(例如在我的第一次插入时)时,创建的序列中的 id 不会增加。

因此,如果我添加一个 id 为 1 的患者,然后添加一个 id 为 NULL 的患者,我会收到错误消息。

有没有办法避免这种情况?还是我必须从我的插入脚本中删除所有 ID?

【问题讨论】:

  • 不提供值。这就是序列的目的。你不能两者都做。插入将使用您传入的任何内容,并且此时对序列不执行任何操作。

标签: sql oracle identity-column


【解决方案1】:

如果您为标识列提供(非空)值,则序列将保持相同的值。这意味着身份可以尝试插入您手动提供的值。

您可以在这里选择几条路径

永远不要为标识列提供值。将其设置为generated always 以确保没有人可以这样做:

create table patient (
   patientid integer             
      generated always as identity (
        start with 1 nocycle order
      )  not null primary key
);

insert into patient 
  values ( 1 );
  
ORA-32795: cannot insert into a generated always identity column

允许脚本提供值,但在使用alter table 后立即将标识的序列重置为列最大值:

drop table  patient 
  cascade constraints purge;
create table patient (
   patientid integer             
      generated by default on null as identity (
        start with 1 nocycle order
      )  not null primary key
);

insert into patient 
  values ( 1 );
insert into patient 
  values ( 11 );
commit;

insert into patient 
  values ( default );
  
ORA-00001: unique constraint (CHRIS.SYS_C0024892) violated
  
alter table patient 
  modify patientid  
  generated by default on null as identity (
     start with limit value 
  );

insert into patient 
  values ( default );

select * from patient;

PATIENTID   
           1 
          11 
          12 

【讨论】:

    猜你喜欢
    • 2015-07-05
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 2015-03-10
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    相关资源
    最近更新 更多