gpt4 book ai didi

SQL-Server:将列定义为互斥

转载 作者:行者123 更新时间:2023-12-02 09:28:20 24 4
gpt4 key购买 nike

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

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

最佳答案

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

ALTER TABLE YourTable
ADD CONSTRAINT ConstraintName CHECK (col1 is null or col2 is null)

根据您的评论,如果许多列是排他性的,您可以这样检查它们:

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

这表示四列之一必须包含一个值。如果它们都可以为NULL,只需检查<= 1 .

关于SQL-Server:将列定义为互斥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1832084/

24 4 0