具有附加关系约束的外键

时间:2014-08-08 07:38:03

标签: sql-server foreign-keys

在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

换句话说,LocationDefect只有在属于同一Client时才能相关。

1 个答案:

答案 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,这是一个品味问题。