Oracle 12c:插入到具有标识列的表中

2022-04-14 00:00:00 oracle12c identity oracle sql-insert ddl

我有一个表,其中一列的类型为Identity Column,它也是主键。

CREATE  TABLE identity_demo  (
    id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
    description VARCHAR2(100) not null
  );

然后我插入几行数据

insert into identity_demo (id, description) values (1,'A');
insert into identity_demo (id, description) values (2,'B');
insert into identity_demo (id, description) values (3,'C');
insert into identity_demo (id, description) values (4,'D');
insert into identity_demo (id, description) values (5,'E');
insert into identity_demo (id, description) values (6,'F');

如果现在要插入未设置值ID的行,则会出现键违规

insert into identity_demo (description) values ('G');
ORA-00001:唯一约束(UWE.IDENTITY_DEMO_PK)版本 在此继续的最佳方式是什么?


解决方案

手动插入的标识值(1到6)与序列生成器生成的标识值之间存在冲突。您可以通过调整序列生成器来修复它:

ALTER TABLE identity_demo MODIFY (
  id GENERATED BY DEFAULT ON NULL AS IDENTITY (START WITH LIMIT VALUE));

START WITH LIMIT VALUE锁定表,查找最高ID并将内部序列生成器设置为下一个较高的值7

如果您不想运行此ALTER TABLE命令,您可以分隔数字空格,比如手工值为1...999,而手动值为1000...用于自动值。您必须这样设置您的发电机:

ALTER TABLE identity_demo MODIFY (
  id GENERATED BY DEFAULT ON NULL AS IDENTITY (START WITH 1000));

INSERT INTO identity_demo (description) VALUES ('H');

...
6      F
7      G
1000   H

相关文章