Sql Server_数据完整性

--数据完整性有四种
--    实体:表中的每一行数据都是一个实体。
--    实体完整性:每一行数据是唯一的不重复的。
--    如何保证实体完整性?
--        1.设置标识列
--        2.设置主键,一个表中只能有一个主键
--        3.设置唯一键: 表中的唯一键可以有多个

--域完整性
--    域就是字段,域完整性指的是必须保证字段的值是合理的。
--  体现:非空 类型 check约束 默认值 关系(主外键约束)

--自定义完整性
--    主外键约束、unique约束 check约束 default约束

--引用完整性 
--    一个表中的某个字段引用另一个表中的字段,被引用的表称为主表,引用表称为从表或外键表。
--    建立主外键联系的字段之间的类型和意义必须一致。
--   主表中建立关系的字段必须是主键或者唯一键。

--主外键表之间的级联操作
--    不执行任何操作:删除主表数据,从表如果没有引用所要删除的主表数据,则可以删除。否则会报错。
--    级联:主表数据的删除 会导致 从表中引用 所要删除的主表数据 的那一行数据 也被删除。
--    set null:主表数据的删除 会导致 从表中的引用字段变为null,前提是 该引用字段可以为null。
--    set default:主表数据的删除 会导致 从表中的字段变为默认值,前提是 该引用字段设置了默认值。

use Test
--判断表Teacher是否存在,存在则删除,以下同理。
if exists(select * from sysobjects where name = 'Teacher')
	drop table Teacher
if exists(select * from sysobjects where name = 'Classes')
	drop table Classes

create table Teacher
(
	Id int identity(1, 1),
	Name nvarchar(50) not null,
	Gender bit not null,
	Age int not null,
	Birthday datetime not null
)

create table Classes
(
	Id int identity(1, 1) primary key,
	Name nvarchar(50) not null
)

--约束种类
--	主键约束(primary key PK) 外键约束(foreign key FK) 
--	唯一键约束(unique UQ) 检查约束(check CK) 默认值约束(default DF) 

--级联删除、更新语法
--	on delete no action / cascade / set null / set default
--	on update no action / cascade / set null / set default

--判断主键PK_Teacher_Id'是否存在,存在则删除。
if exists(select * from sysobjects where name = 'PK_Teacher_Id')
alter table Teacher
drop constraint PK_Teacher_Id

--主键约束
alter table Teacher
add constraint PK_Teacher_Id primary key(Id)
--唯一键约束
alter table Teacher
add constraint UQ_Teacher_Name unique(Name)
--检查约束
alter table Teacher
add constraint CK_Teacher_Age check(Age > 0 and Age <= 100)
--默认值约束
alter table Teacher
add constraint DF_Teacher_Birthday default('2000-1-1') for birthday
--外键约束
--判断外键Fk_Teacher_ClassId是否存在,存在则删除。
if exists(select * from sysobjects where name = 'Fk_Teacher_ClassId')
alter table Teacher
drop constraint Fk_Teacher_ClassId
--
alter table Teacher
with nocheck --不检查已有数据
add constraint Fk_Teacher_ClassId foreign key(ClassId) references Classes(Id)
on delete set null  --级联删除 级联更新

猜你喜欢

转载自blog.csdn.net/hang981601026/article/details/81985241