共計 2464 個字符,預計需要花費 7 分鐘才能閱讀完成。
丸趣 TV 小編給大家分享一下 oracle 中數據完整性的示例分析,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
1. 數據的完整性簡介
就是正確性、準確性,包含三種:實體完整性、參照完整性、
用戶自定義完整性。Oracle 中主要通過約束、觸發器、過程函數
實現的。 以下內容講通過約束實現數據完整性。
舉例兩個表:
學生(學號,姓名,系編號)
系(系編號,系名稱)
員工(編號,姓名,出生日期,工作日期)
那么:
學號是主鍵列,其值不能錯誤,如不能負值,這就是實體完整性;
系編號是外鍵,學生表的系編號參照系表,也就是說學生表的系編號的值必須在系表的系編號的值范圍內【或者為空】,這就是參照完整性;
員工表的出生日期一定需要小宇工作日期,這就是用戶自定義完整性。
2. 維護數據的完整性,有 not null、unique、check、primary key、foreign key 五種。
not null 例如學生的姓名;unique 例如學生的學號;primary key 主鍵、foreign key 外鍵、check 可以按照用戶要求,進行自動檢查。
unique 不可以重復,但是可以為空。
primary key 不可以重復,也不能為空。
一個表只能一個 primary key,卻可以多個 unique。
not null 只能在列內定義,其他 4 種約束可以在列定義結束后,在表內定義。
not null 示例 (這里的 not null 約束由系統自動起名):
create table yg2(bh number(4) not null,xm varchar2(8));
check 示例:
create table yg3(bh number(4) not null check (bh 0 and bh 10000), xm varchar2(8));
unique 示例:
create table yg4(部門號 number(4) not null, 部門內號 number(4) , xm varchar2(8) , unique(部門號, 部門內號) );
default 的使用
create table gz_新員工 (bh number(4),xm varchar2(8),gz number(10) default 1000 ); // 適用于沒有向列顯式的指定數值的情況。
primary key 示例 (此列不允許為空,而且 ORACLE 會自動為主鍵列創建索引,這里的 primary key 約束由用戶顯式起名):
create table student(xh number(6) constraint code_pk primary key , xm varchar2(20));
foreign key 示例 (實現兩個表之間參照與被參照的關系,外鍵只能取主鍵已經有的值,這里的 foreign key 由系統自動起名):
create table address (xh number(8) ,zz varchar2(50) , foreign key(xh) references student(xh));
試驗 primary key 和 foreign key 約束:
insert into student values(1, 張一
insert into address values(1, 鄭州
insert into address values(2, 鄭州
(3) 用戶的約束在 user_constraints 表、和 user_cons_columns 表中
select * from user_constraints;
實踐練習題目:
問題:
建立 2 個表,一個是 StudentInformatino(學號 sno,姓名
sname,年齡 sage,性別 smale,系編號
deptNo),一個是 department(系編號 deptno,
系名稱 deptname)。
要求:
每個表有主鍵。
StudentInformation 表建立外鍵。
學生的姓名不能為空。
學生的年齡要在 18 到 50 之間。
學生的性別必須是男女之一,默認是男。
StudentInformation 表的 deptno 列,要參照 department 表的
deptno 列。
3.2 給已有的表添加約束:
除了添加 not null 需要使用 modify 命令,其他都是類似 alter table tablename add CONSTRAINTS 的方式。
上面例子,允許 stuInfo 中的姓名可以為空:alter table stuinfo modify sname null;
允許 stuInfo 中的姓名不能重復:alter table stuinfo add constraints sname_unique unique(sname) ;
要求 department 的系名稱列的內容,必須大于 4 個字符長度:alter table
department add constraints deptName_check check(length(deptName)
3.3 刪除約束:
alter table 表名 drop constraint 約束名;
alter table department drop constraint deptName_check; — 刪除剛才建立的 department 表上的 deptName_check 約束
刪除主鍵語句:alter table 表名 drop primary key;
如果出錯:ORA-02273: 此唯一 / 主鍵已被某些外鍵引用,可以:alter table department drop primary key cascade;
如果刪除一個主鍵被引用的表,可以:drop table 表名 cascade constraints;
看完了這篇文章,相信你對“oracle 中數據完整性的示例分析”有了一定的了解,如果想了解更多相關知識,歡迎關注丸趣 TV 行業資訊頻道,感謝各位的閱讀!