I've got two tables and I've added a foreign key constraint. Kewl - works great. Now, is it possible to further constrain that relationship against some data in the parent table?
Basically, I have animals in the parent table, and for the child table wishto only contain data where the parent data are .... um .. mammals.
eg.
Animals
^^^^^^^
AnimalId INT PK NOT NULL IDENTITY
AnimalType TINYINT NOT NULL -- 1: Mammal, 2:Reptile, etc..
Name
Mammals
^^^^^^^
AnimalId INT PK FK NOT NULL
NumberOfMammaryGlads TINYINT NOT NULL
So, i wishto make sure that the AnimalId can only be of type Animals.AnimalType = 1
Is this possible??
I don't want to allow someone to try and insert some info against a reptile, in the child table...
Cheers :)
Edit:
I thought I had to use a Check Constraint (confirmed below from my first two answers - cheers!), but I wasn't sure how to (eg. the sql syntax to refer to the Animals table).
Update:
Alex has a very good post (below) that benchmarks some of the suggestions.... a very good read!
I ran a small benchmark - in this case the approach with a UDF runs almost 100 times slower.
The overhead of an FK in CPU time = 375 ms - 297 ms = 78 ms
The overhead of an UDF in CPU time = 7750 ms - 297 ms = 7453 ms
Here's the Sql code...
-- set up an auxiliary table Numbers with 128K rows:
-- the tables
--- populating with UDF:
results are:
--- populating with FK:
results are:
-- populating without any integrity:
results are:
SQL Server parse and compile time: CPU time = 1 ms, elapsed time = 1 ms.
The overhead of an FK in CPU time = 375 ms - 297 ms = 78 ms
The overhead of an UDF in CPU time = 7750 ms - 297 ms = 7453 ms