ORACLE CHECK 約束測試筆記

題目:

create table plch_exam_results (
 exam_id    integer not null,
 student_id integer not null,
 score      integer not null /* TO DO */,
 constraint plch_exre_pk
 primary key (exam_id, student_id)
);

需要在 /* TO DO */ 這裏加上合適的代碼,使得輸入數據庫的score的值是0到100之間的整數。

答案:
1)未命名的check約束

check (score between 0 and 100)

2)有命名的check約束

constraint plch_exre_score_0_100_ck 
check (score between 0 and 100)

約束有名稱後,當運行違反約束條件的語句時,可以更加容易理解錯誤原因。

如果沒有命名的話,sys會在提供此應用程序的不同系統上顯示不同的名字。

如果想要自己通過編寫代碼來查看錯誤並格式化輸出結果的話,沒有命名會導致編寫代碼的過程變得困難。

示例:
在這裏插入圖片描述
3)外鍵約束
外鍵就是引用,實現了引用的完整性,所引用的數據必須存在。
舉例:
首先創建一個plch_scores 表,其列score_id填充1到100的數據;

SQL> create table plch_scores (score_id integer primary key);
Table created
SQL> insert into plch_scores
  2  select rownum - 1 
  3  from dual
  4  connect by level <= 101;
101 rows inserted
SQL> commit;
Commit complete

然後用plch_exam_results2 表中的score列去引用plch_scores表中的score_id列;

SQL> create table plch_exam_results2 (
  2   exam_id    integer not null,
  3   student_id integer not null,
  4   score      integer not null constraint plch_exre_score_fk references plch_scores (score_id),
  5   constraint plch_exre_pk2
  6   primary key (exam_id, student_id)
  7  );
Table created

這裏用到的語法格式:

alter table 表名 add constraint 約束名稱 約束類型 (列名) references 被引用的表名稱 (列名)

測試是否進行了約束;
在這裏插入圖片描述
查看約束具體內容:

 select constraint_name,
 constraint_type,
 table_name,
 search_condition,
 status
 from user_constraints

Oracle之Check約束實例詳解:感覺這一篇已經講解得很基礎,摘抄部分。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章