Reputation: 9580
I need to create a table check constraint to achieve the following:
I've written this constraint, but just wondered if you pro's could cast your expert eyes on it. I have achieve this correctly, or in the best way?
ALTER TABLE MyTable ADD CONSTRAINT [const_name] CHECK
(
(Column1 IS NULL AND Column2 IS NULL) OR
(Column1 IS NOT NULL AND (Column2 IS NOT NULL OR Column2 IS NULL))
)
Upvotes: 0
Views: 151
Reputation: 239684
Simpler form, based on your new rules:
ALTER TABLE MyTable ADD CONSTRAINT [const_name] CHECK
(
(Column2 IS NULL OR Column1 IS NOT NULL)
)
Think about it - if Column2
is null
then we don't need to assert anything about Column1
- it can be NULL
or not and you're happy.
Similarly, if Column1
is not NULL
then we don't care whether Column2
is NULL
or not.
The only case where we want this constraint to fail is specifically when Column2
isn't NULL
but Column1
is - exactly the false case for the above OR
condition.
Upvotes: 2