[英]Sql Server - Constraint - Allow to set column A only if column B is null and vice-versa
Is there a way to add a constraint in SQL Server 2008 that will verify that if a user try to enter a value in a column A, it can only if column B is null and vice-versa 有没有办法在SQL Server 2008中添加一个约束来验证如果用户试图在列A中输入一个值,它只能在列B为空时反之亦然
Example 例
Something like this: 像这样的东西:
ALTER TABLE foo WITH CHECK ADD
CONSTRAINT CK_Foo_reason CHECK (
ColA IS NOT NULL AND ColB IS NULL
OR
ColA IS NULL AND ColB IS NOT NULL
)
Edit: after question update 编辑:问题更新后
It depends if both columns are allowed NULL in which case
这取决于在这种情况下是否允许两列都为NULL
ColA IS NULL OR ColB IS NULL
Edit 2: For 3 columns, exactly one of which must be NOT NULL 编辑2:对于3列,其中一列必须为NOT NULL
No smarty-pants answer I'm afraid. 我担心没有聪明的裤子回答。 I've added spaces to hopefully make it clearer
我添加了空格,希望能让它更清晰
ALTER TABLE foo WITH CHECK ADD
CONSTRAINT CK_Foo_reason CHECK (
ColA IS NOT NULL AND ColB IS NULL AND ColC IS NULL
OR
ColA IS NULL AND ColB IS NOT NULL AND ColC IS NULL
OR
ColA IS NULL AND ColB IS NULL AND ColC IS NOT NULL
)
This seemed to work for me: 这似乎对我有用:
CREATE TABLE dbo.Test_Constraint
(
a INT NULL,
b VARCHAR(10) NULL,
CONSTRAINT Test_Constraint_CHK CHECK (a IS NULL OR b IS NULL)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.