SQL-Server:将列定义为互斥

前端之家收集整理的这篇文章主要介绍了SQL-Server:将列定义为互斥前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想起了一个有趣的场景: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.

原文链接:https://www.f2er.com/mssql/75462.html

猜你在找的MsSQL相关文章