微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

必须会的SQL语句(八) 数据库的完整性约束

实体完整性

1.建表时定义主键

Create table 表名
(
Sno int identity(1,1),
Sname nvarchar(20),
--设置主键
Primary key (Sno)
)

2.添加主键

alter table 表名
add constraint PK_表名_Sno
primary key(id)
参照完整性1.建表时定义外键

create table 表名
(
sno int identity(1,1) primary key,
cno int not null,
foreign key(cno) References
表名2(Cno)
on Delete cascade --级联删除
on update cascade --级联更新
-- on delete on action 删除管制
)

2.添加外键
alter table 表名
add constraint FK_表名_表名2
Foreign key(cid) references 表名2(cid)
用户定义完整性1.非空约束
alter table 表名
alter column name varchar(20) not null

2.唯一约束
alter table 表名
add constraint UQ_表名_列名 unique(列)

3.检查约束
alter table 表名
add constraint CK_表名_列名 check(age>5)

4.认约束
alter table 表名
add constraint DF_表名_列名 default('男')
for gender
删除约束 --删除约束
alter table 表名 drop constraint DF_表名_列

原文地址:https://www.jb51.cc/mssql/63131.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐