I have a table that can be in a 1-* relationship with one of 2 different tables. I currently have it setup where there are 2 nullable columns that reference another table. However, this is causing an issue for cascade deletions.
CREATE TABLE [dbo].[TA] (
[Id] INT IDENTITY (1, 1) NOT NULL,
CONSTRAINT [PK_TA] PRIMARY KEY CLUSTERED ([Id] ASC),
);
CREATE TABLE [dbo].[TB] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[TAId] INT NOT NULL,
CONSTRAINT [FK_TB_To_TA] FOREIGN KEY ([TAId]) REFERENCES [dbo].[TA] ([Id]) ON DELETE CASCADE,
CONSTRAINT [PK_TB] PRIMARY KEY CLUSTERED ([Id] ASC),
);
CREATE TABLE [dbo].[TC] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[TAId] INT NULL,
[TBId] INT NULL,
CONSTRAINT [PK_TC] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_TC_To_TA] FOREIGN KEY ([TAId]) REFERENCES [dbo].[TA] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_TC_To_TB] FOREIGN KEY ([TBId]) REFERENCES [dbo].[TB] ([Id]), -- NOTE: DELETE CASCADE CAUSES A CIRCULAR REFERENCE
);
Essentially, this creates a nested structure like:
TA1
+ -- TC1, TC2
+ -- TB1
+ -- TC3, TC4
A TC object should only be a child of either TA or TB (not both). How should I go about developing this so that I can DELETE a TA row and have all TC and TB referenced rows deleted as well?