【问题标题】:Check if all three columns are either not null or null检查所有三列是否不为空或为空
【发布时间】:2015-04-24 11:34:19
【问题描述】:
我有一个有 4 列的表格:
create table dbo.Table (
Id int not null,
A int null,
B int null,
C nvarchar (4000) null
)
如何确保A、B 和C 都是三个null 或三个not null?
【问题讨论】:
标签:
sql
sql-server
null
sql-server-2012
check-constraints
【解决方案1】:
你可以设置一个check constraint:
constraint [check_abc] check ( ([A] is null and [B] is null and [C] is null) or
([A] is not null and [B] is not null and [C] is not null) )
【解决方案2】:
您还可以考虑将这些相关列分解到第二个表中,在该表中声明它们为not null,并仅在它们适用的地方插入一行。
create table dbo.Table1(
Id int not null primary key
)
create table dbo.Table2(
Id int not null primary key references Table1,
A int not null,
B int not null,
C nvarchar (4000) not null
)