Вот еще один способ решения этой проблемы:
create table dbo.Table1 (
Id int not null primary key clustered,
IsActive bit not null,
ActiveIdForForeignKey as iif(IsActive = 1, Id, -Id) persisted not null,
constraint UQ_ActiveIdForForeignKey unique (ActiveIdForForeignKey)
);
go
create table dbo.Table2 (Id int not null, Table1Id int not null);
go
alter table dbo.Table2 add constraint FK_Table2_Table1 foreign key (Table1Id) references Table1(Id);
alter table dbo.Table2 add constraint FK_Table2_Table1_Active foreign key (Table1Id) references Table1(ActiveIdForForeignKey);
go
insert into dbo.Table1(Id, IsActive) values (1, 0);
insert into dbo.Table1(Id, IsActive) values (2, 1);
insert into dbo.Table1(Id, IsActive) values (3, 0);
go
insert into dbo.Table2(Id, Table1Id) values (1, 2); -- success
insert into dbo.Table2(Id, Table1Id) values (2, 1); -- fail
go
Выглядит как подвох, но это работает без накладных расходов на хранилище данных.
Буду рад услышать ваши комментарии.