SQL-Server:将列定义为互斥

Tho*_*mar 11 sql-server database-design

和同事开玩笑,我提出了一个有趣的场景:在SQL Server中是否可以定义一个表,以便通过"标准手段"(约束等)来确保两个或多个列是互斥的?

我的意思是:我可以确保只有一个列包含值吗?

And*_*mar 15

是的,您可以使用CHECK约束:

ALTER TABLE YourTable
ADD CONSTRAINT ConstraintName CHECK (col1 is null or col2 is null)
Run Code Online (Sandbox Code Playgroud)

根据您的评论,如果许多列是独占的,您可以像这样检查它们:

case when col1 is null then 0 else 1 end +
case when col2 is null then 0 else 1 end +
case when col3 is null then 0 else 1 end +
case when col4 is null then 0 else 1 end
= 1
Run Code Online (Sandbox Code Playgroud)

这表示四列中的一列必须包含值.如果它们都可以为NULL,请检查<= 1.