天天看點

關于oracle資料庫維護資料的完整性--限制

首先是五個限制關鍵字:

1.primary key(主鍵限制):唯一辨別資料庫表中的每條記錄,每個表中有且隻有一個主鍵,且不能為null,它可以包含表中的一個或多個字段(複合主鍵)

2.unique(唯一限制):唯一辨別資料庫表中的每條記錄,每個表中可以有多個unique,可以為null

3.foreign key(外鍵限制):一個表中的 foreign key 指向另一個表中的 primary key

4.check(條件限制):限制用于限制列中的值的範圍

5.not null(非空限制):限制強制列不接受 null 值

下面用一個小的案例來示範他們的用法:

商品goods(商品号goodsId,商品名 goodsName,單價 unitprice,商品類别category,供應商provider);

客戶customer(客戶号customerId,姓名name,住在address,電郵email,性别sex,身份證cardId);

購買purchase(客戶号customerId,商品号goodsId,購買數量nums);

必須包含下面的限制:

(1). 每個表的主外鍵;

(2). 客戶的姓名不能為空值;

(3). 單價必須大于0,購買數量必須在1到30之間;

(4). 電郵不能夠重複;

(5). 客戶的性别必須是 男 或者 女,預設是男;

<pre name="code" class="sql"><strong>/*商品goods(商品号goodsId,商品名 goodsName,單價 unitprice,商品類别category,供應商provider); */
create table goods(
goodsId char(8) primary key,--主鍵限制
goodsName varchar2(40) ,
unitPrice number(10,2) check(unitPrice>0),--check限制
categories varchar2(40),
provider varchar2(40)
);
/*客戶customer(客戶号customerId,姓名name,住在address,電郵email,性别sex,身份證cardId);*/
create table customers(
customerId char(8)primary key,--主鍵限制
customerName varchar2(20) not null,--不為空限制
address varchar2(80),
email varchar2(40) unique,--unique限制
sex char(4) default '男' check(sex in ('男','女')) ,--check限制
cardId char(18)
);</strong>
           

create table purchase(

customerId references customers(customerId),--外鍵限制

goodsId references goods(goodsId),--外鍵限制

nums number check(nums between 1 and 30)--check限制

);

此時出現了新的需求:(修改限制)

(1) 增加商品名也不能為空

<strong>alter table goods modify goodsName not null;--如果要删除not null限制 隻需要把not null改為null
alter table goods modify goodsName null;</strong>
           

(2) 增加身份證也不能重複

<strong>alter table customer add constraint add_unique unique(cardId);--add_unique 隻是為這個添加限制設定的一個名字
/*如果要删除這個限制*/
alter table customer drop constraint add_unique;</strong>
           

(3) 增加客戶的住址隻能是’海澱’,’朝陽’

<strong>alter table customers add constraint add_check check(address in('海澱','朝陽'));
</strong>
           

當你想要删除帶有主外鍵限制的表時:

1.在drop table [表名] 後面加上cascade constraint

drop table customers cascade constraint;
           

2.先删除表的主外鍵限制,再進行表的删除

alter table customers drop primary key cascade;
           

3.先删除子表再删除主表