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

create table dbo.not_null
(
ID int not null,
Name varchar(10) not null
)

2. 默认约束 default

① 创建表 default 约束

create table dbo.default_table -- 创建班级信息表
(
ClassId int not null, -- 班级号不为空
Dept varchar(10) default('软工'), -- 所在系部默认为“软工”
ClassRenshu int default(0) -- 班级人数默认为 0
)


② 修改表 default 约束

alter table dbo.default_table
add constraint df_ClassId default(1001) for ClassId -- constraint 约束关键字 给班级号增加默认值 1001 

 

3. 唯一约束 unique
字段值取值唯一,允许 NULL 值。主键不允许 NULL 值。
① 创建表 unique 约束

create table dbo.unique_table
(
StuID int not null,
sex varchar(10),
StuCard int unique
)

  

② 修改表 unique 约束

alter table dbo.unique_table
add constraint uq_StuID unique(StuID) -- 给 StuID 定义唯一约束

  

4. 检查约束 check
check 约束检查输入的值是否在规定的范围内
① 创建表 check 约束

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 约束

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 约束

create table dbo.Primary_Key
(
StuID int primary key not null,
StuName varchar(10)
)

 

复合主键

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 约束

alter table dbo.Primary_Key
add constraint pk_StuID primary key(StuID)

 

6. 外键约束 Foreign Key
① 创建表 Foreign Key 约束

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 约束

alter table Foreign_Key
add constraint fk_Stuno foreign key(Stu_No) references my.Tb_Stu_Info(Stu_No)

  

7. 删除约束

alter table Foreign_Key
drop constraint fk_Stuno

  

posted @ 2024-03-14 11:37  yinghualeihenmei  阅读(149)  评论(0编辑  收藏  举报