创建学生表Student:
create table Student
(
Sno char(10)primary key, //列级完整性约束条件,Sno是主码
Sname char(10) unique, //Sno取唯一值
Ssex char(2) check (Ssex in ('男','女')), //性别
Sage smallint check(Sage between 18 and 20),//年龄
Sdept char(20),//院系
);
创建课程表Course:
create table Course
(
Cno char(4)primary key, //列级完整性的约束条件 Cno是主码
Cname char(20)not null, //列级完整性的约束条件,Cname不能取空值
Cpno char(4),//先修课
Ccredit smallint,
foreign key (Cpno) references Course(Cno) //表完整性约束条件,Cpno是外码,被参照表是Course,被参照列是Cno
);
创建学生选课表SC:
create table SC
(
Sno char(10),
Cno char(4),
Grade smallint,
primary key(Sno,Cno), //主码由两个属性构成,必须作为表级完整性进行定义
foreign key(Sno) references Student(Sno),表级完整性约束条件,Sno是外码,被参照表是Student foreign key(Cno) references Course(Cno) //表级完整性约束条件,Cno是外码,被参照表是Student );
创建成功结果图:
对数据库中表的内容进行查看:
select * from dbo.Student
select * from dbo.SC
select * from dbo.Course
对数据库中表的内容进行增删查改:
插入:
insert into dbo.Student(Sno, Sname, Ssex, Sage, Sdept)
values('60001','zhangsan','nv',18,'art'),
('60002','lisi','nv',18,'it'),
('60003','wangwu','nv',18,'art'),
('60004','chenliu','nv',18,'pe'),
('60005','tisi','nv',18,'pe');
执行结果: