如何实施“条件外键”限制?

时间:2011-09-23 01:36:23

标签: sql

我有以下表格定义:

CREATE TABLE X (
    A SOMETYPE NOT NULL,
    B SOMETYPE NOT NULL,
    C SOMETYPE NULL,
    PRIMARY KEY (A,B),
    FOREIGN KEY (A) REFERENCES Y (A)
);

我想添加以下约束:如果C IS NOT NULL,则FOREIGN KEY (A,C) REFERENCES X (A,B)。我该怎么做(如果可能的话,不使用触发器)?

我使用的是SQL Server 2008 R2,但这与问题无关。

2 个答案:

答案 0 :(得分:1)

如果我得到了你想要的东西,你需要在表Y中的A上有一个主键,在表Y中有A,B的唯一约束。

试试这个:

create table Y
(
  A int not null,
  B int not null,
  primary key (A)
);

create unique index IX_Y_AB on Y(A, B);

create table X 
(
    A int not null,
    B int not null,
    C int null,
    primary key (A, B),
    foreign key (A) references Y(A),
    foreign key (A, C) references Y(A, B)
);

测试:

insert into Y values (1, 2)

insert into X values (1, 1, null) -- OK
insert into X values (1, 2, 2)    -- OK
insert into X values (1, 3, 3)    -- Fail

答案 1 :(得分:1)

我怀疑你是在过度思考:

CREATE TABLE X (
    A SOMETYPE NOT NULL,
    B SOMETYPE NOT NULL,
    C SOMETYPE NULL,
    PRIMARY KEY (A,B),
    FOREIGN KEY (A) REFERENCES Y (A),
    FOREIGN KEY (A,C) REFERENCES X(A,B)
);

如果引用列(例如C)为空,则不会检查外键。因此,如果C为null,则不检查第二个外键。但如果C不为空,那么A,C必须与同一个表中的A,B组合相匹配。

相关问题