是否可以对表的插入或更新(SQL Server 2008 R2)表示条件验证,如果列B等于12,13或14,则表示列A不能为空。
答案 0 :(得分:7)
您可以使用表级CHECK
constraint实现此目的:
ALTER TABLE YourTable
ADD CONSTRAINT CK_YourCheck
CHECK(ColumnA IS NOT NULL OR ColumnB NOT IN (12, 13, 14))
答案 1 :(得分:1)
是的,您可以使用Check Constraint
执行此操作这样的东西?
ADD CONSTRAINT check validCHECK (
((B BETWEEN 12 and 14) AND A IS NOT NULL)
OR B NOT BETWEEN 12 and 14
);
答案 2 :(得分:0)
在一阶逻辑中,这被称为暗示:
IF x THEN y
应用实施法,上述内容可以转化为:
( NOT ( x ) ) OR y
替换你的表达式:
IF column B is equal to 12,13 or 14 THEN A cannot be null
适用隐私法:
( NOT ( column B is equal to 12,13 or 14 ) ) OR A cannot be null
替换SQL表达式:
( NOT ( B IN (12, 13, 14) ) ) OR ( NOT ( A IS NULL ) )
应用De Morgan的法律:
( NOT x ) OR ( NOT y ) is equivlent to NOT ( x AND y )
因此:
NOT ( B IN (12, 13, 14) AND A IS NULL )
SQL DDL:
ALTER TABLE YourTable ADD
CONSTRAINT your_rule
CHECK ( NOT ( B IN (12, 13, 14) AND A IS NULL ) );