Given four tables:
CREATE TABLE LIST_A (
A INT,
PRIMARY KEY (A)
)
CREATE TABLE LIST_B (
A INT,
B INT,
PRIMARY KEY (A, B),
FOREIGN KEY (A) REFERENCES LIST_A (A)
)
CREATE TABLE LIST_C (
C INT,
A INT,
PRIMARY KEY (C),
FOREIGN KEY (A) REFERENCES LIST_A (A)
)
CREATE TABLE LIST_D (
C INT,
D INT,
B INT,
PRIMARY KEY (C, D),
FOREIGN KEY (C) REFERENCES LIST_C (C)
)
I want to add another constraint: Given a row in LIST_D, whose primary is (C0,D0), and its parent row in LIST_C, whose primary key is C0, the pair (LIST_C.A, LIST_D.B) must reference LIST_B (A, B). How do I implement this in SQL Server 2008 R2?
I think it is important (both for us and for you) to know the the purpose for adding the additional foreign key?
Depending on the exact problem you are trying to solve (data validation on entry, cascading deletes, etc) and the flexibility that you have for solving them (ability or inability to alter the data structure), you could implement logical constraints through triggers. We use this approach at times when we just need to catch edge conditions that should rarely, if ever, occur.
If triggers are insufficient for your situation and foreign keys are required, then about the only option that you have left (without redesigning all of the tables) is to store LIST_C.A into LIST_D and then create the FKey back to LIST_B.
The other option is to redesign it such that you have intermediate tables that contain the appropriate links between all of the tables, but it doesn’t sound like this is desirable.