Answers:
以下应该可以解决问题:
CREATE TABLE MyTable (col1 FLOAT NULL, col2 NVARCHAR(30) NULL, col3 DATETIME NULL);
GO
ALTER TABLE MyTable
ADD CONSTRAINT CheckOnlyOneColumnIsNull
CHECK
(
( 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
) = 1
)
GO
您可能需要在约束内进行三项测试,对于要为空的每一对都要进行一项测试,而对于不应该为null的列进行一项测试:
ALTER TABLE table
ADD CONSTRAINT CK_one_is_null
CHECK (
(col1 IS NOT NULL AND col2 IS NULL AND col3 IS NULL)
OR (col2 IS NOT NULL AND col1 IS NULL AND col3 IS NULL)
OR (col3 IS NOT NULL AND col1 IS NULL AND col2 IS NULL)
);