forum

Home / DeveloperSection / Forums / Foreign key with additional relationship constraint

Foreign key with additional relationship constraint

Anonymous User 1697 21-Jan-2015

In SQL Server 2012, can I create a foreign key constraint that includes a restriction on which rows can be referenced based on other keys?

Example:

CREATE TABLE Client (
    Id    INT IDENTITY PRIMARY KEY
    Description  NVARCHAR(200)
);
 
CREATE TABLE Location (
    Id    INT IDENTITY PRIMARY KEY,
    Description  NVARCHAR(200),
    ClientId  INT NOT NULL,
 
    FOREIGN KEY (ClientId) REFERENCES Client(Id)
);
 
CREATE TABLE Defect (
    Id    INT IDENTITY PRIMARY KEY,
    Description  NVARCHAR(200),
    ClientId     INT NOT NULL,
    LocationId   INT NULL,
 
    FOREIGN KEY (ClientId) REFERENCES Client(Id),
    FOREIGN KEY (LocationId) REFERENCES Location(Id)
);

I would like to constrain Defect.LocationId such that the related Location row must have the same ClientId as the Defect row.

In other words, a Location and Defect can only be related if they belong to the same Client.


Updated on 21-Jan-2015
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By