在本教程中,您将学习如何使用oracle not null
约束强制列不接受null
值。
oracle not null
约束指定列不能包含null
值。 oracle not null
约束是通常在create table
语句的列定义中使用的内联约束。
create table table_name (
...
column_name data_type not null
...
);
可以通过使用alter table语句将not null
约束添加到现有表。
alter table table_name modify ( column_name not null);
在个语句中,在应用not null
约束之后,column_name
不能包含任何null
值。
以下声明创建surcharges
表:
create table surcharges (
surcharge_id number generated by default as identity,
surcharge_name varchar2(255) not null,
amount number(9,2),
primary key (surcharge_id)
);
surcharges
表有三列:附加费用,附加费名称和金额。
surcharge_id
列是由primary key
约束指定的表的主键列,因此,oracle向该列隐式添加not null
约束。
surcharge_name
列具有在列定义中显式指定的not null
约束。amount
列可以接受null
值。
以下语句在surcharges
表中插入一行:
insert into surcharges(surcharge_name, amount)
values('late order placement',10);
它按预期工作。
但是,以下语句不起作用:
insert into surcharges(surcharge_name, amount)
values(null,20);
因为它试图将null
值插入到具有not null
约束的surcharge_name
列中。
以下语句可以正常工作,因为amount
列接受null
值:
insert into surcharges(surcharge_name, amount)
values('rush order',null);
以下语句显示surcharges
表的所有约束条件:
select
table_name,
constraint_name,
search_condition
from
user_constraints
where
table_name = 'surcharges';
如果要将not null
约束添加到amount
列,请使用以下alter table
语句:
alter table surcharges modify (amount not null);
发生类似以下错误:
sql error: ora-02296: cannot enable (ot.) - null values found
因为surcharges
表的数据记录中已经有一行包含null
值。
因此,在添加not null
约束之前,您需要确保附件表中的现有数据不违反not null
约束:
update
surcharges
set
amount = 0
where
amount is null;
现在,如果再次执行alter table
语句:
alter table surcharges modify (amount not null);
它应该按预期工作。
有时,需要更改具有not null
约束的列以接受null
值。
为此,需要使用alter table
语句从列中删除not null
约束,如下所示:
alter table table_name modify ( column_name null)
例如,要从surcharges
表的金额列中删除not null
约束,请使用以下语句:
alter table surcharges
modify (amount null);
在本教程中,您已学习如何使用oracle not null
约束强制列不接受null
值。