SQL Server建库、建表及约束实战指南

竹里
竹里
发布时间:2026-10-13 | 5人浏览过
原创

在数据库开发中,规范化的建库建表流程是保障数据质量的基础。本文介绍如何使用T-SQL在SQL Server中自动化创建数据库,配置数据文件参数,并在学生成绩管理系统场景中构建完整的表结构,通过添加各类约束来实现数据的一致性校验。

创建数据库与文件配置

第1步:判断数据库是否存在并执行创建

为确保脚本可重复执行,通常先检查目标数据库是否已存在。若存在则删除旧实例,否则直接进行新建操作。以下示例演示了如何创建一个名为 School 的数据库,并明确指定主数据文件和日志文件的物理路径及增长策略。

-- 检查School数据库是否存在,存在则删除
if exists(select * from sysdatabases where name = 'School')
drop database School

-- 不存在则创建,配置主数据文件与日志文件
create database School
on primary
(
    name = 'School',          -- 逻辑文件名
    filename = 'D:\project\School.mdf', -- 物理路径
    size = 5MB,               -- 初始大小
    maxsize = 100MB,          -- 最大限制
    filegrowth = 15%          -- 增长率
)
log on
(
    name = 'School_log',
    filename = 'D:\project\School_log.ldf',
    size = 2MB,
    filegrowth = 1MB
);
go

第2步:扩展多文件数据库结构

对于数据量较大的项目,建议将主要数据和次要数据分布在不同文件中,以提高I/O性能。下面展示如何创建带有主文件、次要文件以及多个日志文件的 employee 数据库:

create database employee
on primary
(
    name = 'employee1',
    filename = 'D:\project\employee1.mdf',
    size = 10MB,
    filegrowth = 10%
),
(
    name = 'employee2',      -- 次要数据文件
    filename = 'D:\project\employee2.ndf',
    size = 20MB,
    maxsize = 100MB,
    filegrowth = 1MB
)
log on
(
    name = 'employee_log1',
    filename = 'D:\project\employee_log1.ldf',
    size = 10MB
),
(
    name = 'employee_log2',  -- 第二个日志文件
    filename = 'D:\project\employee_log2.ldf',
    size = 10MB,
    maxsize = 50MB
);

第3步:查询与清理数据库

可以通过系统视图查看当前所有数据库。如需彻底清理环境,可使用 drop database 命令。

-- 查询现有数据库列表
select * from sysdatabases;

-- 删除数据库
drop database School;

构建核心数据表结构

第4步:创建学生基础表 (Student)

切换至 School 库后,删除可能冲突的旧表。定义 Student 表时,需包含学号、登录密码、姓名、联系方式等字段。注意使用 identity 实现自动递增,并为身份证号预留 varchar(18) 空间。

use School;
go

-- 检查并删除旧表
if exists(select * from sysobjects where name = 'Student')
drop table Student;

-- 创建学生表
create table Student
(
    StudentNo int identity(2,1) not null,
    LoginPwd nvarchar(20) not null,
    StudentName nvarchar(20) not null,
    Sex int not null,
    GradeId int not null,
    phone nvarchar(50) not null,
    BornDate datetime not null,
    Address nvarchar(255),
    Email nvarchar(50),
    IDENTITYcard varchar(18)
);
go

第5步:创建课程与年级关联表

建立 subject (课程) 和 Grade (年级) 表。这两张表通常作为被引用的主表,因此后续步骤中将作为外键关系的目标。

-- 创建年级表
if exists(select * from sysobjects where name = 'Grade')
drop table Grade;
create table Grade
(
    GradeId int not null,
    GrandeName nvarchar(50)
);

-- 创建课程表
if exists(select * from sysobjects where name = 'subject')
drop table subject;
create table subject
(
    SubjectNo int not null identity(1,1),
    SubjectName nvarchar(50),
    ClassHour int,
    GradeID int
);

use School;
go

第6步:创建成绩记录表 (Result)

Result 表用于存储考试成绩,包含学生ID、课程ID、考试日期和分数。该表需要建立复合主键以区分不同学生的不同科目成绩。

if exists(select * from sysobjects where name = 'Result')
drop table Result;

create table Result
(
    StudentNo int not null,
    SubjectNo int not null,
    ExamDate Datetime not null,
    StudentResult int not null
);

use School;
go

实施数据约束管理

建表完成后,必须通过 ALTER TABLE 添加约束来保证数据的准确性。以下是常用约束的应用场景。

第7步:为学生表添加通用约束

为主键、唯一字段和逻辑条件添加校验规则。

-- 1. 设置主键
alter table Student
add constraint pk_StuNo primary key(StudentNo);

-- 2. 设置身份证号唯一
alter table Student
add constraint uq_StuIdcard unique(IDENTITYcard);

-- 3. 设置地址默认值
alter table Student
add constraint df_stuaddress default('地址不详') for Address;

-- 4. 检查出生日期是否合理(如大于1980年)
alter table Student
add constraint ck_stuBorndate check(BornDate > '1980-01-01');

如需移除上述默认约束,可使用:
alter table Student drop constraint df_stuaddress;

第8步:建立年级与学生的主外键关系

首先为 Grade 表设置主键,然后在 Student 表中引用它,确保录入的学生等级必须在年级表中存在。

-- 1. 给Grade表加主键
alter table Grade
add constraint pk_graid primary key(GradeId);

-- 2. 给Student表加外键,关联到Grade
alter table Student
add constraint fk_stuGradeID foreign key(GradeId) references Grade(GradeId);

第9步:完善课程表的业务逻辑约束

对课程名称非空和学时大于0进行校验。若表中已有不符合规则的数据,需在语句中加入 with nocheck 跳过历史数据检查。

-- 1. 课程名称不可为空
alter table subject with nocheck
add constraint ck_subName check(SubjectName is not null);

-- 2. 学时必须大于0
alter table subject with nocheck
add constraint ck_ClassHour check(ClassHour > 0);

-- 3. 关联年级
alter table subject with nocheck
add constraint fk_GradeID foreign key(GradeID) references Grade(GradeID);

第10步:组合约束处理成绩表 (Result)

Result 表涉及复杂的关联校验,需同时添加主键(三元组)、默认值、区间检查和两个外键。这些操作可以合并在一个语句中完成。

-- 批量添加多种约束
alter table Result
add 
constraint pk_No_subID_date primary key(StudentNo,SubjectNo,ExamDate),
constraint df_examdate default(getdate()) for ExamDate,
constraint ck_StudentResult check(StudentResult between 0 and 100),
constraint fk_StuNo foreign key(StudentNo) references Student(StudentNo),
constraint fk_subNo foreign key(SubjectNo) references Subject(SubjectNo);

-- 如果未来需要删除多个约束
-- alter table Result drop constraint pk_No_subID_date, fk_subNo, fk_StuNo;

第11步:修改列数据类型

若发现原有字段类型不适合新业务,可以使用 alter column 调整结构。

-- 例如更改Result表中学生成绩的字段属性
alter table Result
alter column StudentResult int;

以上就是SQL Server建库、建表及设置约束的详细内容,更多关于SQL Server进阶操作与数据库优化设计的资料请关注本站其它相关文章!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表