plsql設定欄位可為空 plsql欄位約束

2021-10-16 15:46:58 字數 1993 閱讀 5715

oracle資料庫

orcale開發

oracle技術文章

plsql欄位約束

第五章  字段約束

初識約束

約束是資料庫用來確保資料滿足業務規則的手段,對資料做的條件限制。

約束的型別

1. 主鍵約束(primary key)

2. 唯一性約束(unique)

3. 非空約束(not null)

4. 檢查約束(check)

5. 外來鍵約束(foreign key)

主鍵約束(primary key)

1. 非空加唯一約束;

2. 乙個表只有乙個主鍵;

3. 主鍵會預設加索引;

student_id number primary key

alter table student add constraint stu_id_pk primary key(stu_id);

唯一性約束(unique)

對於unique約束來講,索引是必須的。如果不存在,就自動建立乙個(unique的唯一性本質上是通過索引來保證的)

unique允許null值,unique約束的列可存在多個null。這是因為,unique唯一性通過btree索引來實現,而btree索引中不包含null。所以,這也造成了在where語句中用null值進行過濾會造成全表掃瞄。

student_num  number unique

alter table table_name add constraint student_code_uq unique(student_num);

刪除約束

alter table table_name drop constraint constraint_name;

非空約束(not null)

非空約束作用的列也叫強制列。顧名思義,強制鍵列中必須有值,當然建表時候若使用default關鍵字指定了預設值,則可不輸入。

score_name varchar2(32) not null

alter table table_name modify student_name not null;

檢查約束(check)

檢查約束可用來實施一些簡單的規則,比如列值必須在某個範圍內。檢查的規則必須是乙個結果為true或false 的表示式

student_***    varchar2(1) check(student_*** in('男','女')),

alter table student add constraint stu_***_ck check(stu_*** in('男','女'));

score_value number check(score_value between 0 and 100)

alter table student add constraint stu_age_ck check(stu_age between 1 and 100);

外來鍵約束(foreign key)

外來鍵約束定義在具有父子關係的子表中,外來鍵約束使得子表中的列對應父表的主鍵列,用以維護資料庫的完整性。不過出於效能和後期的業務系統的擴充套件的考慮,很多時候,外來鍵約束僅出現在資料庫的設計中,實際會放在業務程式中進行處理。外來鍵約束注意以下幾點:

外來鍵約束的子表中的列和對應父表中的列資料型別必須相同,列名可以不同對應的父表列必須存在主鍵約束(primary key)或唯一約束(unique)

外來鍵約束在子表裡,外來鍵的取值範圍不能大於父表鍵值

如果想刪除主表的主鍵,需要先刪除子表的關聯字段

student_num  number references table_name(student_num)

alter table student add constraint tea_id_fk foreign key(tea_id) references teacher (tea_id);

注意:不過在真正的企業開發中,除了主鍵約束這類具有強需求的約束,像外來鍵約束,檢查約束更多時候僅僅出現在資料庫設計階段,真實環境卻很少應用,更多是放到程式邏輯中去進行處理。

PL SQL 解釋視窗字段

通過f5檢視到的執行計畫,其實是pl sql developer工具內部執行查詢 plan table表然後格式化的結果。select from plan table where statement id 其中 description列描述當前的資料庫操作,object owner列表示物件所屬使用...

plsql怎麼用字段查表明 PLSQL查詢語句

一 簡單查詢 簡單的transact sql 查詢只包括選擇列表 from 子句和where 子句。它們分別說明所 查詢列 查詢的 表或檢視 以及搜尋條件等。例如,下面的語句查詢 testtable 表中姓名為張三的 nickname 欄位和email 字段。select nickname,emai...

plsql怎麼用字段查表明 PLSQL查詢命令

表的查詢 在此文件中,就按照 student 的表來輸入命令 1.清屏命令 sql clear 2.檢視表的結構 sql desc student 3.查詢表的所有列 sql select from student 這樣查詢的速度 比較慢 4.查詢指定列 sql select xhxm,birthd...