更改 Oracle 主键

问题描述 投票:0回答:1

Oracle 表可能有一个或多个指定为主键的列。该指定在创建表时发生。假设该表有多个列作为其主键的一部分,并且其中一些列是外键。 1)我们可以更改表的主键并将某些外键设置为空(即将它们从非空更改为空)吗? 2)是否建议在创建后更改 oracle 表的主键?

这是一个理论问题。我正在尝试获得专业人士的建议和经验。

oracle foreign-keys primary-key
1个回答
0
投票

您可以更改属于主键一部分的列,并将其标记为

NULL
(可用),但由于您在其上定义了主键 (P) 约束,因此如果
NULL
值仍然会被拒绝插入。主键不允许在其列中出现
NULL
值:

create table tmp1 (col1 integer not null, col2 integer not null, constraint pk_tmp1 unique (col1));
create table tmp2 (col1 integer not null, col2 integer not null, constraint pk_tmp2 primary key (col1), constraint fk_col1 foreign key (col1) references tmp1(col1));
alter table tmp2 modify (col1 null); -- this succeeds
insert into tmp1 values (1,100);
insert into tmp2 values (null,200); -- this however still fails

但是,您可以删除主键约束并在其位置创建唯一 (U) 约束。唯一的键确实允许

NULL
作为允许的值:

alter table tmp2 drop constraint pk_tmp2;
alter table tmp2 add constraint uk_tmp2 unique (col1);
insert into tmp2 values (null,200); -- this now works

但是,请考虑一些奇怪的行为:

如果

NULL
值位于唯一约束的 only 列中,则不会强制执行。您可以根据需要插入任意数量的
(null,200)
行,它会允许的。然而,如果唯一约束是列约束,则其中一列中的
NULL
将充当离散值,并且仅允许一个
NULL
(其他列相同)。

此外,FK 约束的

any
列中的 NULL 将导致 FK 约束不执行任何操作。即使父表中没有相应的
NULL
,您也可以在子表中插入
NULL

© www.soinside.com 2019 - 2024. All rights reserved.