I looked over several posts here on stack overflow about SQL Server error 1785: Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths. And I found that it is a Microsoft product feature not to check for cycles and the common recommendation is to get around it with triggers.
So my question was:
How do I generate Foreign Key dependancies on multiple tables in SQL Server?
By mistake, I found that if I create a separate independent PRIMARY KEY, I can create the table with multiple cascade paths without an error (and it works functionally as expected). For reference I am running SQL Server 2019.
The following generates an error:
CREATE TABLE t1 (
id bigint,
CONSTRAINT PK_t1 PRIMARY KEY CLUSTERED (id)
);
CREATE TABLE t2 (
id bigint,
CONSTRAINT PK_t2 PRIMARY KEY CLUSTERED (id)
);
CREATE TABLE cross_t1_t2 (
t1_id bigint,
t2_id bigint,
CONSTRAINT PK_cross_t1_t2 PRIMARY KEY CLUSTERED (t1_id,t2_id),
CONSTRAINT FK_cross_t1_t2_t1 FOREIGN KEY (t1_id)
REFERENCES customers (id)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT FK_cross_t1_t2_t2 FOREIGN KEY (t2_id)
REFERENCES addresses (id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
Since I couldnt find this answer anywhere I am posting it here as an alternative to the trigger workaround. It would be nice to know why this is happening.