views:

33

answers:

3

Is there a way to add a constraint in SQL Server 2008 that will verify that if a user try to enter a value in a column A, it can only if column B is null and vice-versa

Example

  • if A is NULL, B can have a value
  • if B iS NULL, A can have a value
  • A and B can't have value at the same time
+3  A: 
gbn
Reading his question it seemed to me that he only wants one to be NOT NULL at a time
Tom H.
@Tom H: true. This is my 2nd case which matches yours which allows both NULL.
gbn
If I got 3 values, let say a Column C, what will be the constraint condition ?
Melursus
A: 

You can set up a trigger to check for this.

Bob Zirkowski
A: 

This seemed to work for me:

CREATE TABLE dbo.Test_Constraint
(
    a INT NULL,
    b VARCHAR(10) NULL,
    CONSTRAINT Test_Constraint_CHK CHECK (a IS NULL OR b IS NULL)
)
Tom H.
Good call on my answer Tom. I forgot all about that.
treefrog