您可能希望使用 Identities - 创建具有标识的表使您有机会省略 ID 值并让 Oracle 在所需列上使用序列:
1.让我们创建表:
CREATE TABLE identities (
id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
description varchar2(100) NOT NULL
);
表已创建。
2。您需要创建一个主键以确保唯一性:
alter table identities add constraint id_pk primary key (ID);
表已更改。
3.让我们以不同的方式插入一些数据:
INSERT INTO identities (description)
VALUES('Insert Description omitting ID');
已创建 1 行。
INSERT INTO identities (id,description)
VALUES(NULL,'Insert with explicit NULL value');
已创建 1 行。
4.保存完成的工作
commit;
提交完成。
5.检查结果
select * from identities;
ID DESCRIPTION
---------- ---------------------------------------------
1 Insert Description omitting ID
2 Insert with explicit NULL value
如您所见,我们没有为 ID 指定任何数字,但 ID 列上的 Identity 为我们指定了任何数字
注意:请注意,您可以手动插入ID,但这会与Identity 混淆,就像通常使用标准Sequence 一样:
INSERT INTO identities (id,description)
VALUES(3,'Manually insert an ID value');
1 row created.
INSERT INTO identities (description)
VALUES('Test Nextval');
INSERT INTO identities (description)
*
ERROR at line 1:
ORA-00001: unique constraint (XXX.ID_PK) violated
这个错误,因为它试图在之前用语句手动插入的 ID 中插入一个“3”。
查看表格:
select * from identities;
ID DESCRIPTION
---------- ---------------------------------------------
1 Insert Description omitting ID
2 Insert with explicit NULL value
3 Manually insert an ID value
重新运行“NEXTVAL”插入:
INSERT INTO identities (description)
VALUES('Test Nextval');
已创建 1 行。
重新检查表格:
select * from identities;
ID DESCRIPTION
---------- ---------------------------------------------
1 Insert Description omitting ID
2 Insert with explicit NULL value
3 Manually insert an ID value
4 Test Nextval
希望对您有所帮助。