Sqlserver中所有约束的类型,创建、修改与删除
1、 https://blog.51cto.com/u_15738244/5535432
2、 https://blog.csdn.net/realoser/article/details/121496126
数据库所有的约束:
一、主键约束(primary key)
二、外键约束(foreign key)
三、检查约束(check)
四、非空约束(not null)
五、唯一性约束(unique)
六、默认值约束(default)
创建、修改与删除:
1. 非空约束 Not Null
1 2 3 4 5 | create table dbo.not_null ( ID int not null , Name varchar (10) not null ) |
2. 默认约束 default
① 创建表 default 约束
1 2 3 4 5 6 | create table dbo.default_table -- 创建班级信息表 ( ClassId int not null , -- 班级号不为空 Dept varchar (10) default ( '软工' ), -- 所在系部默认为“软工” ClassRenshu int default (0) -- 班级人数默认为 0 ) |
② 修改表 default 约束
1 2 | alter table dbo.default_table add constraint df_ClassId default (1001) for ClassId -- constraint 约束关键字 给班级号增加默认值 1001 |
3. 唯一约束 unique
字段值取值唯一,允许 NULL 值。主键不允许 NULL 值。
① 创建表 unique 约束
1 2 3 4 5 6 | create table dbo.unique_table ( StuID int not null , sex varchar (10), StuCard int unique ) |
② 修改表 unique 约束
1 2 | alter table dbo.unique_table add constraint uq_StuID unique (StuID) -- 给 StuID 定义唯一约束 |
4. 检查约束 check
check 约束检查输入的值是否在规定的范围内
① 创建表 check 约束
1 2 3 4 5 6 | create table dbo.check_table ( StuID int not null , Score numeric check (Score>=0 and Score<=100), -- numeric 数字型,int 整数型 |check(Score between 0 and 100) Setdate date ) |
② 修改表 check 约束
1 2 3 | alter table dbo.check_table add constraint ch_Setdate check (Setdate between '2001-1-1' and '2002-1-1' ) -- add constraint ch_Setdate check(Setdate>='2001-1-1' and Setdate<='2002-1-1') |
5. 主键约束 Primary Key
① 创建表 Primary Key 约束
1 2 3 4 5 | create table dbo.Primary_Key ( StuID int primary key not null , StuName varchar (10) ) |
复合主键
1 2 3 4 5 6 7 | create table dbo.Primary_Key2 ( StuID int not null , CourseID int not null , Score numeric not null , constraint pk_StuID_CourseID primary key (StuID,CourseID) ) |
② 修改表 Primary Key 约束
1 2 | alter table dbo.Primary_Key add constraint pk_StuID primary key (StuID) |
6. 外键约束 Foreign Key
① 创建表 Foreign Key 约束
1 2 3 4 5 6 | create table Foreign_Key ( StuID int primary key not null , StuName varchar (10), Stu_No varchar (12) foreign key references my.Tb_Stu_Info(Stu_No) -- references 连接到某个表的某个主键 ) |
② 修改表 Foreign Key 约束
1 2 | alter table Foreign_Key add constraint fk_Stuno foreign key (Stu_No) references my.Tb_Stu_Info(Stu_No) |
7. 删除约束
1 2 | alter table Foreign_Key drop constraint fk_Stuno |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2023-03-14 使用 pdf.js 在网页中加载 pdf 文件