gpt4 book ai didi

甲骨文 12c : Insert into Table with Identity Column

转载 作者:行者123 更新时间:2023-12-04 04:11:16 25 4
gpt4 key购买 nike

我有一个表,其中有一列类型为标识列,这也是主键。

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)在这里进行的最佳方式是什么?

最佳答案

首先,似乎有一部分,CONSTRAINT IDENTITY_DEMO_PK PRIMARY KEY (id)

添加到建表DDL的末尾。

只需删除 BY DEFAULT ON NULL 部分,以便将身份生成的管理留给 DBMS,同时将 ID 列保留为 PRIMARY KEY。在这种情况下,您应该从插入语句中的列列表中删除 ID 列,如

INSERT INTO identity_demo (description) VALUES ('G'); :

SQL> CREATE  TABLE identity_demo  (
2 id NUMBER GENERATED AS IDENTITY,
3 description VARCHAR2(100) NOT NULL,
4 CONSTRAINT IDENTITY_DEMO_PK PRIMARY KEY (id)
5 );

Table created

SQL> BEGIN
2 INSERT INTO identity_demo (id, description) VALUES (1,'A');
3 INSERT INTO identity_demo (id, description) VALUES (2,'B');
4 INSERT INTO identity_demo (id, description) VALUES (3,'C');
5 INSERT INTO identity_demo (id, description) VALUES (4,'D');
6 INSERT INTO identity_demo (id, description) VALUES (5,'E');
7 INSERT INTO identity_demo (id, description) VALUES (6,'F');
8 END;
9 /

ORA-32795: cannot insert into a generated always identity column
ORA-06512: at line 3

SQL> INSERT INTO identity_demo (description) VALUES ('G');

1 row inserted

SQL> SELECT * FROM identity_demo;

ID DESCRIPTION
---------- -------------------------------------------------------
1 G

SQL> BEGIN
2 INSERT INTO identity_demo (description) VALUES ('A');
3 INSERT INTO identity_demo (description) VALUES ('B');
4 INSERT INTO identity_demo (description) VALUES ('C');
5 INSERT INTO identity_demo (description) VALUES ('D');
6 INSERT INTO identity_demo (description) VALUES ('E');
7 INSERT INTO identity_demo (description) VALUES ('F');
8 END;
9 /

PL/SQL procedure successfully completed

SQL> SELECT * FROM identity_demo;

ID DESCRIPTION
---------- --------------------------------------------------------
1 G
2 A
3 B
4 C
5 D
6 E
7 F

7 rows selected

关于甲骨文 12c : Insert into Table with Identity Column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61682294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com