views:

23

answers:

1

to simplify this let take that table:

 table1
 -------------
 id unique primary int
 myVal1 int null (fk)
 myVal2 int null (fk)
 myData int not null

what would be the best way to create a constrain on this table so only one value can be filled?

these would work:

insert into table1 (myval1,myData) values (1,234)
insert into table1 (myval2,myData) values (1,123)

these would not work:

insert into table1 (myData) values (234)
insert into table1 (myVal1,myval2,myData) values (1,2,123)
+1  A: 

try using a check constraint:

CREATE TABLE dbo.Table1
    (
    rowID int NOT NULL primary key identity(1,1),
    myVal1 int NULL,
    myVal2 int NULL,
    myData int NOT NULL
    )  ON [PRIMARY]
GO
ALTER TABLE dbo.Table1 ADD CONSTRAINT
    CK_Table1_myVal1_or_myVal2 CHECK ((myVal2 IS NOT NULL AND myVal1 IS NULL) OR (myVal2 IS NULL AND myVal1 IS NOT NULL))
GO
KM
going to test that in a few hour, can't right now so if it work like I want, you will get the green check
Fredou