Click here to Skip to main content
15,893,486 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi. i've got some problems during creating a user table and friend table.
AppUser table (general user info):
Id (int),
FirstName (varchar),
LastName (varchar)

and Friend table
Id (int),
AFriendId (int),
BFriendId (int)

and there are two foreign keys on AFriendId and BFriendId to AppUser.Id
i set cascade on update and delete for both.
the table is not saving, says that i must change on update and delete no no action. any ideas how to fix this problem?
Posted
Updated 21-Feb-15 8:42am
v2
Comments
CHill60 21-Feb-15 13:54pm    
Why would you want a cascade update?
Arlert 21-Feb-15 13:57pm    
because if id will change, it must change on both tables
[no name] 21-Feb-15 14:46pm    
"I must Change", no you do not have to. Read CHil60's comment! If you define it as cascaded you are out of pb.
CHill60 21-Feb-15 15:07pm    
It's not a good idea to change id fields
Arlert 21-Feb-15 15:17pm    
if i set no action on update, the problem is still unresolved

1 solution

On update cascade is just normal. If you change referred ID for any reason (why should you?) - the referring foreign key will be updated.
On delete cascade is also normal as when one person is deleted, all of hes/her friednship relations should be deleted too.
Well, what you desire is just normal.
Still, you can't assure with DDL, that the two foreign keys are not referring the same record in the other table. This is for some reason unacceptable for MSSQL Server - it complains about situations that can't appear.

Still, if you try the same thing in MySQL, PostgreSQL it will work without restriction. It is not your fault - your design is not wrong.

Add both foreign key constraints with "no action" and implement trigger(s) instead of trying to rely on DDL enforced action. Something like this:
SQL
CREATE TRIGGER AppUser_AD
ON dbo.AppUser
AFTER DELETE AS
BEGIN
 DELETE FROM dbo.Friend 
 WHERE 
	AFriendId in (SELECT id FROM DELETED) 
	OR 
	BFriendId in (SELECT id FROM DELETED) 
END
GO
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900