在SQL Server 2012中,我是否可以创建一个外键约束,其中包含对可以根据其他键引用哪些行的限制?
示例:
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)
);
我想约束Defect.LocationId
,以使相关的Location
行必须与ClientId
行具有相同的Defect
。
换句话说,Location
和Defect
只有在属于同一Client
时才能相关。
答案 0 :(得分:0)
在Location
中创建一个超级键:
CREATE TABLE Location (
Id INT IDENTITY PRIMARY KEY,
Description NVARCHAR(200),
ClientId INT NOT NULL,
FOREIGN KEY (ClientId) REFERENCES Client(Id),
CONSTRAINT UQ_Location_Client_XRef UNIQUE (Id,ClientId)
);
然后将其用作Defect
中外键的附加或替代:
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), --<-- Redundant
constraint FK_Defect_Location_Client_XRef FOREIGN KEY
(LocationId,ClientId) REFERENCES Location(Id,ClientId)
);
您是否真正删除了多余的FK,这是一个品味问题。