SQL Server 2008 - Multiple Cascading FK's - Do i need a trigger? -


i have 1..* relationship between user , post. (one user has many posts)

post has fk called "userid", maps "userid" field on user table.

i tried set fk cascade update/delete, error:

'users' table saved 'posts' table - unable create relationship 'fk_posts_users'.
introducing foreign key constraint 'fk_posts_users' on table 'posts' may cause cycles or multiple cascade paths. specify on delete no action or on update no action, or modify other foreign key constraints. not create constraint. see previous errors.

i have table called posthelpful. 1 post has many helpful's.

helpful has cascading fk user (so when user deleted, helpful's deleted).

but think cause of complaint "multiple cascade paths".

because if delete user (currently), delete helpfuls. im trying add cacade post also, delete post, try , delete helpful's post (as helpful has cascading fk post). in scenario, cascading fk sql choose?

here database diagram of 3 tables in question:

enter image description here

as can see, "posthelpful" child both "post" , "user" (has fk's both).

so can't make both keys cascading? need trigger on "users" (after delete) manually delete helpfuls (and other tables referencing user).

it's not matter of path sql server choose, not allow won't wind in compromising position. when ran situation, had resort trigger.

1) error message stated, change users_posthelpfuls fk on delete no action.

2) add instead of delete trigger users:

create trigger dbo.users_io_delete  on dbo.users instead of delete begin;     delete dbo.posthelpfuls userid in (select userid deleted);      delete dbo.users userid in (select userid deleted); end; 

now, fk still enforce dri, trigger cascading delete rather fk constraint.

you replace posthelpfuls posts in above steps. when doing it's best use trigger remove less independent entity's records. in other words, it's more posts related tables beside users , posthelpfuls posthelpfuls related tables beside users , posts.


Comments

Popular posts from this blog

Javascript line number mapping -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -