# 数据库实验3

《数据库原理与技术》实验三SQL语言的DDL

1.打开数据库SQL Server 2008的查询分析器，用Create Table建表Student，course，sc。数据库的名称为“学生选课”，各个表结构如教材P85页所示。

CREATE DATABASE学生选课

ON

(NAME='学生选课_dat',

FILENAME='D:\data\学生选课_dat.mdf')

LOG ON

(NAME='学生选课_Log',

FILENAME='D:\data\学生选课_Log.ldf ')

USE学生选课

CREATE TABLE Student(

Sno CHAR(9)PRIMARY KEY,

Sname CHAR(20)UNIQUE,

Ssex CHAR(2),

Sage SMALLINT,

Sdept CHAR(20)

);

CREATE TABLE Course

(Cno CHAR(4)PRIMARY KEY,

Cname CHAR(40),

Cpno CHAR(4),

Ccredit SMALLINT,

FOREIGN KEY (Cpno)REFERENCES Course(Cno)

);

CREATE TABLE SC

(SNo CHAR(9),

CNo CHAR(4),

Grade SMALLINT,

PRIMARY KEY (SNo,CNo),

FOREIGN KEY (Sno)REFERENCES Student(Sno),

FOREIGN KEY (Cno)REFERENCES Course(Cno));

2.向表中填入教材P82数据。

INSERT INTO Student VALUES('200215121','李勇','男',20,'CS'); INSERT INTO Student VALUES('200215122','刘晨','女',19,'CS'); INSERT INTO Student VALUES('200215123','王敏','女',18,'MA'); INSERT INTO Student VALUES('200215125','张立','男',19,'IS'); INSERT INTO Course VALUES('1','数据库','5',4);

INSERT INTO Course VALUES('2','数学',null,2);

INSERT INTO Course VALUES('3','信息系统','1',4);

INSERT INTO Course VALUES('4','操作系统','6',3);

INSERT INTO Course VALUES('5','数据结构','7',4);

INSERT INTO Course VALUES('6','数据处理',null,2);

INSERT INTO Course VALUES('7','PASCAL语言','6',4);

INSERT INTO SC VALUES('200215121','1',92);

INSERT INTO SC VALUES('200215121','2',85);

INSERT INTO SC VALUES('200215121','3',88);

INSERT INTO SC VALUES('200215122','2',90);

INSERT INTO SC VALUES('200215122','3',80);

3.向Student 表增加“入学时间”列（列名为Scome,日期型）ALTER TABLE Student ADD Scome DATE；

4.将年龄的数据类型改为整型。

ALTER TABLE Student ALTER COLUMN Sage INT;

5. 为Student中sname添加列级完整性约束，不能为空。为Student中sno添加列级完整性约束，取值唯一，不能为空

ALTER TABLE Student ADD CONSTRAINT C1CHECK (Sname is not null);

ALTER TABLE Student ADD CONSTRAINT C2CHECK (Sno is not null); ALTER TABLE Student ADD UNIQUE(Sno);

ALTER TABLE Student DROP CONSTRAINT C1;

7.为SC建立按学号升序和课程号降序建立唯一索引ALTER TABLE Student DROP CONSTRAINT C1;

CREATE UNIQUE INDEX SCno ON SC(Sno ASC,Cno DESC);

8. 建立Student、Course及SC的主码约束

ALTER TABLE Student ADD CONSTRAINT C3primary key (Sno);

ALTER TABLE Course ADD CONSTRAINT C4primary key (Cno);

ALTER TABLE sc ADD CONSTRAINT C5primary key (Sno,Cno);

alter table sc add constraint c3foreign key (sno)references student

(sno);

alter table sc add constraint c4foreign key (cno)references course(cno);

10.实现学生性别只能是“男”或“女”的Check(检查)约束。

ALTER TABLE Student ADD CONSTRAINT C5CHECK(Ssex in('男','女'))

11.实现学生年龄只能小于等于30大于17的语义约束

ALTER TABLE Student ADD CONSTRAINT C6CHECK (Sage>17 and Sage<=30);

12. 用Create Index对表student的sname字段建立一个升序索引，索引名Indexs。

create index indexs on student(sname asc);

13．用Drop Index删除索引Indexs。

DROP INDEX INDEXS ON Student;