I have a table with 4 columns (ID (PK, int, NOT NULL), col1 (NULL), col2 (NULL), col3 (NULL))
I like to add a CHECK constraint (at the table level, I think?) So that:
if col1 OR col2 are NOT NULL then col3 must be NULL
and if col3 is NOT NULL, then col1 AND col2 must be NULL
i.e. col3 must be null if col1 and col2 are not zero or vice versa
I am very new to SQL and SQL Server, although Iβm not sure how to really implement this or even if it can / should be implemented?
I think maybe:
CHECK ( (col1 NOT NULL OR col2 NOT NULL AND col3 NULL) OR (col3 NOT NULL AND col1 NULL AND col2 NULL) )
But I'm not sure if parentheses can be used to group logic as follows?
If not, how is this best implemented?
sql sql-server check-constraints
Toby
source share