SQL Server 建库,表,约束(一)

要点:

1.GO是用来分割批处理的语句.而局部变量的范围仅限于一个批处理内,在GO之后就不能使用之前定义的变量

2.创建数据库 CREATE DATABASE studentManager 和 生成主数据文件,日志文件之间 不要加GO语句,加了的话,会报错,生成不了 主次数据文件,和日志文件

3.一个数据库中,只可以有一个 主数据文件(扩展名: .mdf),多个次数据文件(扩展名: .ndf),多个日志文件(扩展名: .Ldf)

studentManager.mdf

USE mastergo–查找全部数据库中 如果有 名为 studentManager 则删除if exists (SELECT * FROM sysdatabases WHERE name = ‘studentManager’)drop database studentManagergoCREATE DATABASE studentManager–这里不要加GO语句,,加了的话,生成不了 主数据文件,和日志文件onprimary –主数据文件(name = ‘studentManager’, fileName = ‘D:\SQLServer\Data\studentManager.mdf’, size = 5 MB , maxSize = 50 MB , fileGrowth = 1 MB)– 这里还可以加 次数据文件,扩展名为 .ndflog on –日志文件( name = ‘studentManager_log’, fileName = ‘D:\SQLServer\Data\studentManager_log.ldf’, size = 5 MB , maxSize = 50 MB , fileGrowth = 1 MB )– 这里还可以加多个日志文件,扩展名为 .ldfgoUSE studentManagergo–建 主表create table student( –字段名 数据类型 约束(一般在此只加非空约束)stuId int identity not null , — identity 标识符 自增 1stuName varchar(10) not null ,stuAge int not null ,stuTel varchar(11) not null,stuAddress varchar(20),groupId int not null)go–建子表create table exam(examId int identity not null ,stuId int not null , –外键writeResult int ,computerResult int )go–给表添加约束条件alter table studentadd constraint pk_stuIdprimary key (stuId), –主键约束constraint ch_stuAgecheck (stuAge>=0 and stuAge<=60), –check约束constraint ch_stuTel –check约束check (stuTel like ‘[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]’),–check约束 用了通配符constraint DE_stuAddress –default约束default ‘地址不详’ for stuAddressgoalter table examadd constraint pk_examIdprimary key (examId),constraint ch_writeResultcheck (writeResult>=0 and writeResult<=100),constraint ch_computerResultcheck (computerResult>=0 and computerResult<=100),–设外键constraint exam_stuIdforeign key (stuId)references student(stuId)go

版权声明:本文为博主原创文章,未经博主允许不得转载。

销售世界上第一号的产品——不是汽车,

SQL Server 建库,表,约束(一)

相关文章:

你感兴趣的文章:

标签云: