1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| # [例 5.7] Student 表的 Ssex 只允许取“男”或“女”。 CREATE TABLE Student ( Sno CHAR(9) PRIMARY KEY, Sname CHAR(8) NOT NULL, Ssex CHAR(2) CHECK (Ssex IN ('男', '女')), Sage SMALLINT, Sdept CHAR(20) );
# [例 5.8] SC 表的 Grade 的值应该在 0 和 100 之间。 CREATE TABLE SC ( Sno CHAR(9), Cno CHAR(4), Grade SMALLINT CHECK (Grade >= 0 AND Grade <= 100), PRIMARY KEY (Sno, Cno), FOREIGN KEY (Sno) REFERENCES Student (Sno), FOREIGN KEY (Cno) REFERENCES Course (Cno) );
# [例 5.9]当学生的性别是男时,其名字不能以 Ms.打头。 CREATE TABLE Student ( Sno CHAR(9), Sname CHAR(8) NOT NULL, Ssex CHAR(2) CHECK (Ssex IN ('男', '女')), Sage SMALLINT, Sdept CHAR(20), PRIMARY KEY (Sno), CHECK (Ssex = '女' OR Sname NOT LIKE 'Ms.%') );
# [例 5.10]建立学生登记表 Student,要求学号在 90000~99999 之间,姓名不能取空值,年龄小于 30,性别只能是“男”或“女”。 CREATE TABLE Student ( Sno NUMERIC(6) CONSTRAINT C1 CHECK (Sno BETWEEN 90000 AND 99999), Sname CHAR(20) CONSTRAINT C2 NOT NULL, Sage NUMERIC(3) CONSTRAINT C3 CHECK (Sage < 30), Ssex CHAR(2) CONSTRAINT C4 CHECK (Ssex IN ( ‘男’,'女')), CONSTRAINT StudentKey PRIMARY KEY (Sno) );
# [例 5.11]建立教师表 TEACHER,要求每个教师的应发工资不低于 3000 元。应发工资是工资列 Sal 与扣除项 Deduct 之和。 CREATE TABLE TEACHER ( Eno NUMERIC(4) PRIMARY KEY, Ename CHAR(10), Job CHAR(8), Sal NUMERIC(7, 2), Deduct NUMERIC(7, 2), Deptno NUMERIC(2), CONSTRAINT TEACHERFKey FOREIGN KEY (Deptno) REFERENCES DEPT (Deptno), CONSTRAINT C1 CHECK (Sal + Deduct >= 3000) );
# [例 5.12]去掉例 5.10 Student 表中对性别的限制。 ALTER TABLE Student DROP CONSTRAINT C4; # [例 5.13] 修改表 Student 中的约束条件,要求学号改为在 900000~999999 之间,年龄由小于 30 改为小于 40 可以先删除原来的约束条件,再增加新的约束条件 ALTER TABLE Student DROP CONSTRAINT C1; ALTER TABLE Student ADD CONSTRAINT C1 CHECK (Sno BETWEEN 900000 AND 999999); ALTER TABLE Student DROP CONSTRAINT C3; ALTER TABLE Student ADD CONSTRAINT C3 CHECK (Sage < 40);
|