(1)创建数据库ScoreDB (2)创建表Class、Student、 Course、Term、Score,按(3)-(9)设置各表的实体完整性、参照完整性和用户自定义完整性(表结构详见教材P67) (3)设置Class, Student, Course, Term, Score五张表的主键 (4)设置Student, Course, Score三张表的外键 (5)设置Class表“ClassName”列和Course表“CourseName”列的唯一性约束 (6)设置Class表的“ClassNo”第1、2位为A-Z的英文字母,其余只能为数字字符 (7)设置Student表的 “Sex”值只能为男或女,默认值为“女”;年龄不能小于17岁 (8)设置Score表的“Score”列的值在[0,100]之间 (9)设置Course表“creditHour”列的值等于“courseHour”列的值除以16
时间: 2024-01-07 08:04:21 浏览: 241
(完整版)学生成绩管理系统数据库表结构说明 (2).pdf
好的,以下是创建ScoreDB数据库和五张表,以及设置完整性约束的SQL命令:
1. 创建数据库ScoreDB:
```
CREATE DATABASE ScoreDB;
```
2. 切换到ScoreDB数据库:
```
USE ScoreDB;
```
3. 创建表Class:
```
CREATE TABLE Class (
ClassNo CHAR(4) PRIMARY KEY CHECK (ClassNo LIKE '[A-Z][A-Z][0-9][0-9]'),
ClassName VARCHAR(20) UNIQUE NOT NULL,
HeadTeacher VARCHAR(10) NOT NULL
);
```
4. 创建表Student:
```
CREATE TABLE Student (
StudentNo CHAR(8) PRIMARY KEY,
StudentName VARCHAR(10) NOT NULL,
Sex CHAR(2) DEFAULT '女' CHECK (Sex IN ('男', '女')),
Birthday DATE NOT NULL,
ClassNo CHAR(4) NOT NULL,
FOREIGN KEY (ClassNo) REFERENCES Class (ClassNo) ON UPDATE CASCADE ON DELETE CASCADE
);
```
5. 创建表Course:
```
CREATE TABLE Course (
CourseNo CHAR(4) PRIMARY KEY,
CourseName VARCHAR(20) UNIQUE NOT NULL,
CreditHour INT NOT NULL,
CourseHour INT NOT NULL,
FOREIGN KEY (CourseNo) REFERENCES Score (CourseNo) ON UPDATE CASCADE ON DELETE CASCADE
);
```
6. 创建表Term:
```
CREATE TABLE Term (
TermNo CHAR(4) PRIMARY KEY,
TermName VARCHAR(20) UNIQUE NOT NULL,
BeginDate DATE NOT NULL,
EndDate DATE NOT NULL
);
```
7. 创建表Score:
```
CREATE TABLE Score (
StudentNo CHAR(8) NOT NULL,
CourseNo CHAR(4) NOT NULL,
TermNo CHAR(4) NOT NULL,
Score INT CHECK (Score BETWEEN 0 AND 100),
PRIMARY KEY (StudentNo, CourseNo, TermNo),
FOREIGN KEY (StudentNo) REFERENCES Student (StudentNo) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (CourseNo) REFERENCES Course (CourseNo) ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (TermNo) REFERENCES Term (TermNo) ON UPDATE CASCADE ON DELETE CASCADE
);
```
8. 设置Class表“ClassName”列和Course表“CourseName”列的唯一性约束:
```
ALTER TABLE Class ADD CONSTRAINT uc_ClassName UNIQUE (ClassName);
ALTER TABLE Course ADD CONSTRAINT uc_CourseName UNIQUE (CourseName);
```
9. 设置Class表的“ClassNo”第1、2位为A-Z的英文字母,其余只能为数字字符:
```
ALTER TABLE Class ADD CONSTRAINT ck_ClassNo CHECK (ClassNo LIKE '[A-Z][A-Z][0-9][0-9]');
```
10. 设置Student表的“Sex”值只能为男或女,默认值为“女”;年龄不能小于17岁:
```
ALTER TABLE Student ADD CONSTRAINT ck_Sex CHECK (Sex IN ('男', '女'));
ALTER TABLE Student ADD CONSTRAINT df_Sex DEFAULT '女' FOR Sex;
ALTER TABLE Student ADD CONSTRAINT ck_Age CHECK (DATEDIFF(YEAR, Birthday, GETDATE()) >= 17);
```
11. 设置Score表的“Score”列的值在[0,100]之间:
```
ALTER TABLE Score ADD CONSTRAINT ck_Score CHECK (Score BETWEEN 0 AND 100);
```
12. 设置Course表“creditHour”列的值等于“courseHour”列的值除以16:
```
ALTER TABLE Course ADD CONSTRAINT df_CreditHour DEFAULT (CourseHour / 16) FOR CreditHour;
```
以上命令将创建ScoreDB数据库和五张表,并设置完整性约束。您可以根据需要修改表结构和完整性约束。
阅读全文