Note: this question appears to have been asked before at Cascade delete on many-to-many between same table but didn't receive a satisfactory answer.
I have a table, Friendship( MemberId, FriendId ), which allows a Member to add another Member as a friend.
CREATE TABLE dbo.FRIENDSHIP(
MemberId INT NOT NULL
, FriendId INT NOT NULL
, DateCreated DATE NOT NULL DEFAULT CURRENT_TIMESTAMP
CONSTRAINT pk_friendship PRIMARY KEY( MemberId, FriendId ),
CONSTRAINT fk_friendship_member FOREIGN KEY( MemberId ) REFERENCES Member( MemberId ) ON DELETE CASCADE,
CONSTRAINT fk_friendship_friend FOREIGN KEY( FriendId ) REFERENCES Member( MemberId ) ON DELETE CASCADE
);
When I run this script, I see the following error:
Introducing FOREIGN KEY constraint 'fk_friendship_friend' on table 'FRIENDSHIP' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Obviously, I want records in Friendship to be deleted whenever either member is deleted; I also don't want either field to be nullable.
After some research, I saw people suggesting the use of Triggers. So I created one:
CREATE OR ALTER TRIGGER friendship_cascade_delete
ON Member
FOR DELETE
AS
DELETE FROM Friendship
WHERE MemberId IN( SELECT MemberId
FROM deleted )
OR FriendId IN( SELECT MemberId
FROM deleted );
but when I go to delete a Member, I still get the error:
The DELETE statement conflicted with the REFERENCE constraint "fk_friendship_member". The conflict occurred in database "CVGS", table "dbo.FRIENDSHIP", column 'MemberId'.
So it's not even getting to the point where it can fire the trigger. If I remove fk_friendship_member and fk_friendship_friend, the trigger works properly - but I'm not sure I want to remove those constraints.
Is there any way to get the behaviour I want, without risking invalid rows in the table or unnecessary SQL errors? Am I missing something obvious here?