加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 09:21:02 所属栏目:MsSql教程 来源:网络整理
导读:实体完整性 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 表名 (

实体完整性

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_表名_列

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读