维护数据的完整性
数据的完整性确保数据库数据遵从一定的商业和逻辑规则。早oracle中数据的完整性可以使用约束、触发器、应用程序(过程、函数)三种方法实现。约束效果最好
约束:
not null、unique、primary key、foreign key、check
商店表的设计:
商品goods:(goodsId、goodsName、price、category、provider);
客户customer:(customerId,name,address,email,sex,cardId);
订单purchase:(customerId,goodsId,numbers);
//创建商品表
create table goods(goodsId char(10) primarykey,--主键
goodsname varchar2(16) not null,
price number(8,2) check(price>0),
category varchar2(10),
provider varchar2(16));
//客户表
create table customer(customerId char(8)primary key,--主键
name varchar2(30) not null,
address varchar2(50),
email varchar2(20) unique,
sex number(1) defulte 1 check(sex in(1,2)),--1代表男,2代表女
cardId char(18) );
//订单表
create table puechase(customerId char(8)references custermer(customerId),--外健
goodsId char(10) referencs goods(goodsId),
numbers number(2) check (munbers between 1and 30) );
为已经建好的表增加约束
alter table命令为表增加约束(在增加not null时要是用modify选项,增加其他的四种约束使用add选项)
alter table goods modify category not null;--为category列增加not null约束
alter table customer add constraintcardunique unique(cardId);--为cardId增加unique约束
alter table customer add constraintaddresscheck check(address in(‘陕西’,’上海’,’北京’));--设置check约束
删除约束
alter table 表名 drop constraint 约束名称;
在删除主键时,可能有错误(两张表存在主从关系,那么删除主表的约束时,必须带上cascade选项)
alter table 表名 drop primary keycascade;
显示约束的信息:
1. 通过查询数据字典user_contraints可以显示当前用户的所有约束信息
select constraint_name,constraint_type,status, validatedfrom user_contraints where table_name=’表名’
2. 显示约束列
通过查询数据字典user_cons_columns,可以显示约束对应的表列信息
select colum_name,position from user_cons_columns whereconstraint_name=’约束名’
列级定义:
在定义列的同时定义约束//在定义列紧跟着定义约束
表级定义:
在定义所有列之后,在定义约束,这里需要注意,not null只能是列级约束//先设置列,等列都设置好了,再添加约束。