You can do it with some computed columns, but it doesn't look very pretty:
CREATE TABLE A (
A_UNIQUE_ID int NOT NULL PRIMARY KEY,
A_OTHER_ID int NOT NULL,
A_CURRENT_FL bit NOT NULL,
OTHER_XREF as CASE WHEN A_CURRENT_FL = 1 THEN A_OTHER_ID END persisted,
UNIQ as CASE WHEN A_CURRENT_FL = 0 THEN A_UNIQUE_ID ELSE 0 END persisted
constraint UQ_OTHER_XREF UNIQUE (OTHER_XREF,UNIQ)
)
INSERT INTO A VALUES (1, 1, 0);
INSERT INTO A VALUES (2, 1, 0);
INSERT INTO A VALUES (3, 1, 1);
CREATE TABLE B (
B_UNIQUE_ID int NOT NULL PRIMARY KEY,
A_OTHER_ID int NOT NULL,
XREF as 0 persisted,
constraint FK_B_A FOREIGN KEY (A_OTHER_ID,XREF) references A (OTHER_XREF,UNIQ))
This works:
insert into B VALUES (2,1)
This breaks the FK constraint:
insert into B VALUES (3,2)
The two computed columns in table A ensure that any row with A_CURRENT_FL
= 1
has that as a distinct value in OTHER_XREF
. Other rows will have NULL
in that column. However, to apply a UNIQUE
constraint (the target for the foreign key), we need something that will be distinctly different for every row with a NULL
, whilst being a well-known value for the row with A_CURRENT_FL
= 1
. In this case, I made the well known value 0
.
Finally, the foreign key constraint needs to match both of these columns, so we add a new computed column in table B with the well known value 0
.
Column names aren't particularly good, but I'm sure you can come up with some.
Note, also, that by the above, we've also implemented another constraint that you didn't mention, but that also may be important - there can't be two rows now in table A that both have A_CURRENT_FL
set to 1, for the same A_OTHER_ID
value. This also generates an error:
INSERT INTO A VALUES (4,1,1);