----1)创建一个名为s_t1的数据库
create database s_t1
use s_t1
create table student
(Sno char(9) primary key ,
Sname char(6) not null,
Ssex char(2),
Sage int,
Sdept varchar(8));
create table course
(
Cno char(4) primary key,
Cname varchar(20) not null,
Cpno char(4) ,
Ccreat int
)
create table sc
(
Sno char(9) ,
Cno char(4) ,
Grade int ,
primary key (Sno,Cno)
)
----2) 在course表中为cpno列添加外键约束,约束名为”FK_cpno_course”,参照course表的主键cno。
alter table course
add constraint FK_cpno_course foreign key (Cpno) references course(Cno);
----3) 在sc表中为sno列添加外键约束,约束名为”FK_sno_student”参照student表的主键sno,为cno列添加外键约束,约束名为”FK_cno_course”,参照course表的主键cno。
alter table sc
add constraint FK_sno_student foreign key (Sno) references student(Sno)
alter table course
add constraint FK_cno_course foreign key (Cno) references course(Cno)
----4) 在表student中增加新字段 “班级名称(sclass)”, 类型为varchar,长度为10;
alter table student
add sclass varchar(10);
----5) 在表student中删除字段“班级名称(sclass)”;
alter table student drop column sclass ;
----6) 修改表student中字段名为“sname”的字段长度由原来的6改为8;
alter table student
alter column sname char(8);
----7) 修改表student中字段“sdept”名称为“dept”,长度为20;
alter table student
alter column Sdept varchar(20)
exec sp_rename 'student.Sdept','dept','column';
----8) 在表student中为sage字段添加一个名为“CK_sage”的核查约束,限定年龄的取值为16-40。
alter table student
add constraint CK_sage Check (sage between 16 and 40) ;
----9) 在表student中删除约束“CK_sage”。
alter table student
drop constraint CK_sage;
----10) 修改表student中sage字段名称为sbirth,类型为smalldatetime;
alter table student
alter column sage smalldatetime
exec sp_rename 'student.sage', 'sbirth','column';
----11) 修改表student新名称为stu_info;
exec sp_rename 'student','stu_info';
----12) 删除数据表stu_info。
drop table 'stu_info';
数据库实验八
最新推荐文章于 2023-12-21 18:06:56 发布
本文介绍了如何使用SQL创建数据库、添加外键约束、表结构修改、字段增删改等操作,包括创建student、course和sc表,添加外键,调整表结构,如字段类型、长度和约束,并演示了数据库表名变更和删除。
摘要由CSDN通过智能技术生成