oracle維護資料的完整性

2021-08-08 20:43:26 字數 2506 閱讀 1955

oracle維護資料的完整性(約束)

在oracle中,約束包括:not null,unique,primary key,

foreign key 和check五種.

a)not null:即非空

b)unique(唯一):當定義了唯一約束後,該列值是不能重複的,

但是可以為null

c)primary key:即為主鍵,當定義主鍵約束後,該列不但不能

重複而且不能為null

需要說明的是:一張表最多只能有乙個主鍵,但是可以有多個

unqiue約束

d)foreign key:即為外來鍵

e)check:用於強制資料必須滿足的條件 比如資料在某些範圍之內

以乙個商店售貨系統表設計案例來說明上述約束的用法:

商品goods表(商品號goodsid,商品名goodsname,單價unitprice,

商品類別category,**商provider)

客戶customer表(客戶號customerid,姓名name,住址address,

電郵email,性別***,身份證cardid);

在定義中要求宣告:

1)每個表的主外來鍵

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

3)單價必須大於0,購買數量必須在1到30之間

4)電郵不能夠重複

5)客戶的性別必須是男 或者 女,預設是男

建表的sql指令碼語句如下:

create table goods(

2  goodsid char(8) primary key,--主鍵

3  goodsname varchar2(30),

4  unitprice number(10,2) check(unitprice > 0),

5  category varchar2(50),

6  provider varchar2(30));

create table customer(

2  coustomerid char(8) primary key,--主鍵

3  name varchar2(50) not null,

4  address varchar2(50),

5  email varchar2(50) unique,

6  ***  char(2) default '男' check (*** in ('男','女')),

7  cardid char(18));

table created

create table purchase(

2  customerid char(8) references customer(customerid),

3  goodsid char(8) references goods(goodsid),

4  nums number(10) check (nums between 1 and 30));

oracle維護資料的完整性(維護)

如果在建表時忘記建立必要的約束,則可以在建表後使用alter table命令為

表增加約束.但是要注意:增加not null約束時,需要使用modify選項,而增加

其它四種約束則使用add選項

以上面的案例為例子:

如:增加商品名也不不能為空

alter table goods modify goodsname not null;

身份證不能是重複的

alter table customer add constraint(約束) cardunique(約束的名字,可隨意取) unique(cardid);

增加客戶的住址只能是'東城' 或者'西城'

alter table customer add constraint addresscheck check (address in ('東城,西城'));

刪除約束:

alter table 表名 drop constraint 約束的名字;

在刪除主鍵約束的時候,可能有錯誤 如:

alter table 表明 drop primary key;

這是因為如果在兩張表存在主從關係,那麼在刪除主表的主鍵

約束時,必須帶上cascade選項 如:

alter table 表名 drop primary key cascade;

oracle維護資料的完整性(表級定義和列級定義)

a)列級定義:

列級定義是在定義列的同時定義約束

如:create table department(

dept_id number(2) constraint pk_department primary key

);b)表級定義:

表級定義是指在定義了所有列後,再定義約束.這裡需要注意:not null

約束只能在列級上定義.

如:create table employee

(id number(2),

constraint pk_employee primary key (id)

);

oracle資料完整性

資料完整性 約束,索引,許可權和角色 資料完整性 資料完整性用以確保資料庫資料遵從一定的商業和邏輯規則。在oracle中,資料完整性可以使用約束 觸發器 應用程式 過程和函式 三種方法來實現,這三種方法中,因為約束易於維護,並且具有最好的效能,所以作為維護資料完整性的首選。約束 約束用以確保資料庫資...

資料表的完整性,維護資料的完整性(約束),標識列

維護資料表的完整性 標識列1.實體完整性 每個表中有乙個必須要指定的字段,主要依賴主鍵約束 2.區域完整性 針對表中的某個字段進行特殊化限制,主要依賴剩餘的約束 3.參照完整性 表與表之間的一種特殊化關聯限制,主要依靠外來鍵約束 什麼是約束 使用約束 鍵的作用來維護資料表的完整性 約束有哪些 自增約...

oracle資料完整性約束

在oracle資料庫中建立表的同時,我們需要給字段新增 約束條件 注意 orcale資料庫中新增約束的條件跟sql server mysql不完全一樣。實體完整性 主鍵 新增主鍵約束 primary key alter table 表名 add constraint 約束名稱 約束型別 關聯列名 a...