Max
Max

Reputation: 20004

SQL Server NULL constraint

Is is possible in SQL Server 2008 to create such a constraint that would restrict two columns to have NULL values at the same time? So that

Column1 Column2
NULL    NULL   -- not allowed
1       NULL   -- allowed
NULL    2      -- allowed
2       3      -- allowed

Upvotes: 10

Views: 4532

Answers (1)

gbn
gbn

Reputation: 432261

ALTER TABLE MyTable WITH CHECK 
   ADD CONSTRAINT CK_MyTable_ColumNulls CHECK (Column1 IS NOT NULL OR Column2 IS NOT NULL)

As part of the create

CREATE TABLE MyTable (
 Column1 int NULL,
 Column2 int NULL,

 CONSTRAINT CK_MyTable_ColumNulls CHECK (Column1 IS NOT NULL OR Column2 IS NOT NULL)
)

Upvotes: 14

Related Questions