创建三个基础表

本文档提供了一个SQL脚本,用于在MS SQL Server中创建三个基本表:学生表(Student)、课程表(Course)和成绩表(SC)。脚本包含了表的定义、主键和外键约束设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



/*文件名称:createtable.sql
*功能:        创建创建3个基本表:Student、Course、SC。
*创建时间:    2008-4-12
*创建人:        XSing
*最后修改时间:    2008-4-12
*/

use [testdatabase]
if exists(select 1 from sysobjects where [id] = object_id(N'[dbo].[Student]')
and objectproperty([id],N'IsUserTable')=1)
drop table [dbo].[Student]
go
if exists(select 1 from sysobjects where [id] = object_id(N'[dbo].[Course]')
and objectproperty([id],N'IsUserTable')=1)
drop table [dbo].[Course]
go
if exists(select 1 from sysobjects where [id] = object_id(N'[dbo].[SC]')
and objectproperty([id],N'IsUserTable')=1)
drop table [dbo].[SC]
go
/*object_id(),objectproperty()是MS SQL的内置函数
object_id()用于获取对象ID
objectproperty()用于查询对象信息
*
where后面的条件语句等号左面不一定是列名,也可以是经过计算的列,如上:
where ... and objectproperty([id],N'IsUserTable')=1
当然,where后面的条件语句不只等值判断,也可以是其它判断语句,
如不等值判断,存在判断或不存在判断
*/


create table [dbo].[Student]
(
Sno 
varchar(7not null,--学号
Sname varchar(8),--姓名
Ssex bit,--性别
Sbirthday smalldatetime--出生日期
)
go
create table [dbo].[Course]
(
Cno 
varchar(5not null,--编号
Cname varchar(16),--名称
Ccredit smallint,--学分
Cpc varchar(5)--先行课程ID,暂定为只有一个或者无先行课程
)
go
create table [dbo].[SC]
(
Sno 
varchar(7not null,
Cno 
varchar(5not null,
Grade 
smallint--成绩
)
go

/*创建约束
主键可以是一个列,也可以是多个列
设置外键的时候,默认不进行关联删除和更新,要自行设定
*/


--创建主键
alter table Student add constraint Student_PK primary key(Sno)
go
alter table Course add constraint Course_PK primary key(Cno)
go
alter table SC add constraint SC_PK primary key(Sno,Cno)
go
--创建外键
alter table SC add constraint SC_FK_S foreign key(Sno)
references Student(Sno) on delete cascade on update cascade
go
alter table SC add constraint SC_FK_C foreign key(Cno)
references Course(Cno)
go




 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值