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

来源:互联网 发布:淘宝网修改快递单号 编辑:程序博客网 时间:2024/05/29 05:55

要点:

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 标识符 自增 1     stuName 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 student   add constraint pk_stuId             primary key (stuId), --主键约束       constraint ch_stuAge             check (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 exam   add constraint pk_examId             primary key (examId),       constraint ch_writeResult             check (writeResult>=0 and writeResult<=100),       constraint ch_computerResult             check (computerResult>=0 and computerResult<=100),       --设外键       constraint exam_stuId            foreign key (stuId)            references student(stuId)go