您的位置:首页 > 数据库

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

2013-08-05 10:00 330 查看
use master --设置当前数据库为master,以便访问sysdatabases表
go

if exists(select * from sysdatabases where name='MySchool')
drop database MySchool

--建库
create database MySchool
on 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 Student

create 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 Result

create table Result
(
StudentNO int not null
)
go

--建约束
--添加主键约束(将StudentNo作为主键)
alter table Student
add constraint pk_stuNo primary key (StudentNo)

--添加唯一约束
alter table Student
add constraint uq_stuID unique (IdentityCard)

--添加默认约束
alter table Student
add constraint df_stuAddress default ('地址不详') for [Address]

--添加检查约束
alter table Student
add constraint ck_stuBornDate check (BornDate >= '1980-01-01')

--添加外键约束(主表Student和从表Result建立关系,关联列为StudentNo)
alter table Result
add constraint fk_stuNo foreign key (StudentNo) references Student(StudentNo)

go

--删除约束
alter table Student
drop constraint df_stuAddress


SQL分类:

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

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

DCL—数据控制语言(GRANT,REVOKE,COMMIT,ROLLBACK)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: