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约束实例详解:感觉这一篇已经讲解得很基础,摘抄部分。

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