Constraint3:check约束 和 null

Check约束用以限制单列或多列的可能取值范围。

1,在check约束中(check(expression)),如果expression返回的结果是Unknown,那么check返回的结果是true。

create table dbo.dt_check
(
    id int null constraint ck_ID_is_Positive check(id>0)
)


插入数据,测试check约束的工作机制

复制代码
insert into dbo.dt_check
values(null)

insert into dbo.dt_check
values(1)

insert into dbo.dt_check
values(0)
复制代码

消息 547,级别 16,状态 0,第 2 行
INSERT 语句与 CHECK 约束"ck_ID_is_Positive"冲突。该冲突发生于数据库"db_study",表"dbo.dt_check", column 'id'。
语句已终止。

NULL和1 插入成功,而0插入失败。

2,Check 约束分为table level和 column level,table level对多列的可能取值进行限制

复制代码
create table dbo.dt_check
(
    id int null ,
    code int null,
    constraint ck_IDCode_is_Positive check(id>0 and code >0)
)
复制代码

在一个已经创建的table上,通过alter table来增加,修改和删除check约束,添加的约束是table level 的约束。

create table dbo.dt_check
(
    id int null ,
    code int null
)

3,增加check约束

alter table dbo.dt_check
add constraint ck_ID_is_Positive check(id>0)

4,删除check约束

alter table dbo.dt_check
drop constraint ck_ID_is_Positive

5,修改Check约束,必须先drop 约束,然后add check约束

alter table dbo.dt_check
drop constraint ck_ID_is_Positive

alter table dbo.dt_check
add constraint ck_ID_is_Positive check(id>0)


6,通过alter table 增加column,并在column上增加column level的check 约束

alter table dbo.dt_check
add  sex char(1) not null
constraint ck_sex check(sex in('M','F'))
原文地址:https://www.cnblogs.com/wangsicongde/p/7551282.html