使用SQL语句建库、建表、建约束

来源:互联网 发布:银行家算法实验报告 编辑:程序博客网 时间:2024/05/29 04:17
use master --设置当前数据库为master,以便访问sysdatabases表go if exists(select * from sysdatabases where name='MySchool')   drop database MySchool  --建库create database MySchoolon primary  --默认就属于primary主文件组,可省略(  --主数据文件的具体描述  name='MySchool_data',                   --主数据文件的逻辑名称,存在master数据库下  filename='G:\DB\MySchool_data.mdf',     --主数据文件的物理名称  size=3mb,                               --主数据文件的初始大小  maxsize=100mb,                          --主数据文件增长的最大值  filegrowth=15%                          --主数据文件的增长率),(  --次要数据文件的具体描述  name='MySchool2_data',                  --次要数据文件的物理名称  filename='G:\DB\MySchool2_data.ndf',    --次要据文件的物理名称  size=3mb,                               --次要据文件的初始大小  maxsize=100mb,                          --次要据文件增长的最大值  filegrowth=1mb)log on(  --日志文件1的具体描述,各参数含义同上  name='MySchool_log',  filename='G:\DB\MySchool_log.ldf',  size=1mb,  filegrowth=1mb),(  --日志文件2的具体描述,各参数含义同上  name='MySchool2_log',  filename='G:\DB\MySchool2_log.ldf',  size=1mb,  filegrowth=1mb)go                                        --和后续的SQL语句分隔开use MySchool  --将当前数据库设置为MySchool,以便在MySchool数据库中创建表go--建表if exists(select * from sysobjects where name='Student')  drop table Studentcreate table Student  /*创建学生信息表*/(  StudentNo int not null,             --学号,非空(必填)  LoginPwd nvarchar(20) not null,     --登录密码  StudentName nvarchar(20) not null,  --学生姓名,非空  Sex bit not null,                   --性别,取值0或1  GradeId int not null,               --年级编号  Phone nvarchar(50) null,            --联系电话,允许为空,即可选输入  [Address] nvarchar(255) null,       --住址,允许为空,即可选输入  BornDate datetime not null,         --出生日期  Email nvarchar(50) null,            --邮箱帐号,允许为空,即可选输入  IdentityCard varchar(18) not null   --省份证号)go--建成绩表if exists(select * from sysobjects where name='Result')  drop table Resultcreate table Result(  StudentNO int not null)go--建约束--添加主键约束(将StudentNo作为主键)alter table Studentadd constraint pk_stuNo primary key (StudentNo)--添加唯一约束alter table Studentadd constraint uq_stuID unique (IdentityCard)--添加默认约束alter table Studentadd constraint df_stuAddress default ('地址不详') for [Address]--添加检查约束alter table Studentadd constraint ck_stuBornDate check (BornDate >= '1980-01-01')--添加外键约束(主表Student和从表Result建立关系,关联列为StudentNo)alter table Resultadd constraint fk_stuNo foreign key (StudentNo) references Student(StudentNo)go--删除约束alter table Studentdrop constraint df_stuAddress


SQL分类:

DDL—数据定义语言(CREATE,ALTER,DROP,DECLARE) 

DML—数据操纵语言(SELECT,DELETE,UPDATE,INSERT) 

DCL—数据控制语言(GRANT,REVOKE,COMMIT,ROLLBACK)  

原创粉丝点击