一、场景
给定一个场景,学生选课系统为例,大家很熟悉。
主要关系:
学生(学号、姓名、年龄、性别)
教师(教师ID,教师姓名)
课程(课程ID,课程名称,任教教师ID)
成绩(学生ID,课程ID,成绩)
二、创建表并预置数据
创建关系表:
--学生:Student(SID,SName,SAge,SSex)
--学生表(学号、姓名、年龄、性别)
--性别,0表示男,1表示女
--
--IF EXISTS(SELECT OBJECT_ID('Student')) /*此处永远为true,原因是OBJECT_ID返回具体ID,或者NULL*/
--使用下列语句,如果没有,什么都不返回,也就不存在
IF EXISTS(SELECT id FROM sysobjects WHERE name='Student')
DROP Table Student
Create table Student
(
SID nvarchar(20) primary key not null,
SName nvarchar(20),
SAge int,
SSex bit
)
--教师:Teacher(TID,TName)
--教师表(教师ID,教师姓名)
IF EXISTS(SELECT id FROM sysobjects WHERE name='Teacher')
Drop table Teacher
GO
Create table Teacher
(
TID nvarchar(20) primary key not null,
TName nvarchar(20) not null,
)
--课程:Course(CID,CName,TID)
--课程表(课程ID,课程名称,任教教师ID)
IF EXISTS(SELECT id FROM sysobjects WHERE name='Course')
BEGIN
DROP Table Course
END
Create table Course
(
CID nvarchar(20) primary key not null,
CName nvarchar(50) not null,
TID nvarchar(20)
)
IF EXISTS(SELECT id FROM sysobjects WHERE name='SC')
DROP TABLE SC
--成绩:SC(SID,CID,Score)
--成绩表(学生ID,课程ID,成绩)
Create table SC
(
SID nvarchar(20) not null,
CID nvarchar(20) not null,
Score int
)
alter table SC add constraint PK_SC primary key(SID,CID)
预置数据
这里仅仅是个例子,针对不同的题目,可以预置适当的数据进行检测。
/*预置数据*/
DELETE FROM Student
INSERT INTO Student(SID,SName,SAge,SSex) VALUES('S001','Tom','20','0')
INSERT INTO Student(SID,SName,SAge,SSex) VALUES('S002','Lucy','21','1')
INSERT INTO Student(SID,SName,SAge,SSex) VALUES('S003','Jim','18','0')
INSERT INTO Student(SID,SName,SAge,SSex) VALUES('S004','Brush','20','0')
INSERT INTO Student(SID,SName,SAge,SSex) VALUES('S005','Kim','22','1')
INSERT INTO Student(SID,SName,SAge,SSex) VALUES('S006','Fka','20','0')
INSERT INTO Student(SID,SName,SAge,SSex) VALUES('S007','Cidy','17','1')
INSERT INTO Student(SID,SName,SAge,SSex) VALUES('S008','YouNi','19','0')
GO
DELETE FROM Teacher
INSERT INTO Teacher(TID,TName) VALUES('T001','张三')
INSERT INTO Teacher(TID,TName) VALUES('T002','李四')
INSERT INTO Teacher(TID,TName) VALUES('T003','王五')
GO
DELETE FROM Course
INSERT INTO Course(CID,CName,TID) VALUES('C01','英语','T001')
INSERT INTO Course(CID,CName,TID) VALUES('C02','体育','T002')
INSERT INTO Course(CID,CName,TID) VALUES('C03','数学','T003')
GO
DELETE FROM SC
INSERT INTO SC(SID,CID,Score) VALUES('S001','C01','78')
INSERT INTO SC(SID,CID,Score) VALUES('S001','C02','60')
INSERT INTO SC(SID,CID,Score) VALUES('