/**//*文件名称: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]goif exists(select 1 from sysobjects where [id] = object_id(N'[dbo].[Course]')and objectproperty([id],N'IsUserTable')=1)drop table [dbo].[Course]goif 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()用于获取对象IDobjectproperty()用于查询对象信息*where后面的条件语句等号左面不一定是列名,也可以是经过计算的列,如上:where ... and objectproperty([id],N'IsUserTable')=1当然,where后面的条件语句不只等值判断,也可以是其它判断语句,如不等值判断,存在判断或不存在判断*/create table [dbo].[Student](Sno varchar(7) not null,--学号Sname varchar(8),--姓名Ssex bit,--性别Sbirthday smalldatetime--出生日期)gocreate table [dbo].[Course](Cno varchar(5) not null,--编号Cname varchar(16),--名称Ccredit smallint,--学分Cpc varchar(5)--先行课程ID,暂定为只有一个或者无先行课程)gocreate table [dbo].[SC](Sno varchar(7) not null,Cno varchar(5) not null,Grade smallint--成绩)go/**//*创建约束主键可以是一个列,也可以是多个列设置外键的时候,默认不进行关联删除和更新,要自行设定*/--创建主键alter table Student add constraint Student_PK primary key(Sno)goalter table Course add constraint Course_PK primary key(Cno)goalter 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 cascadegoalter table SC add constraint SC_FK_C foreign key(Cno)references Course(Cno)go