【SQL server数据库基础】约束类型

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YoXE7HYI-1636032215914)(.\SQL 案例图片\7 约束.png)]

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

主文章:备考计算机三级数据库——SQL 案例

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iFulling

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值