views:

57

answers:

2

I have three tables in my database: Events, Jobs, and CollectableEntities.

Events has a nullable FK pointing to Jobs' PK.

Events and Jobs both have non-nullable FKs (that are also those table's PKs) pointing to CollectableEntities' PK. These FK relationships are set to cascade on update and delete. Basically, when you delete a CollectableEntity, I want the associated Event and/or Job to be deleted also.

I am now trying to change the Events to Jobs FK relationship to set null on update or delete, but I get the following error:

Error SQL01268: .Net SqlClient Data Provider: Msg 1785, Level 16, State 0, Line 1 Introducing FOREIGN KEY constraint 'FK_Events_Jobs' on table 'Events' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

Where is the cycle? How can I avoid this problem given that the description above is the only effects I want. (I'm willing to make changes to avoid other unforeseen side-effects.)

+2  A: 

it would probably just be a lot easier to mark everything as "deleted" instead of actually deleting data out of the database. so on your tables you would have a bit field called Deleted that defaults to false. Then, whenever something is deleted that record gets marked as deleted. After that you just set up a where statement in your queries to removed the deleted items and you're done.

DForck42
Not what I'm looking for, but it could work.
David Pfeffer
also with this methodology you don't run the risk of ruining your referential integrety or loss of data.
DForck42
In my case I'm storing over 10,000 records per hour, so for space considerations I really do need to actually purge the old ones. For people who don't care about the size bloat of their database though, this could work so long as the Deleted column is indexed.
David Pfeffer
+2  A: 

See the http://allyourdatabase.blogspot.com/2006/11/multiple-cascade-paths-error-in-sql.html

You have a very similar situation... deleting from collectables is going to attempt a delete from events, which is going to attempt a delete from jobs due to the FK from events to jobs. But deleting from collectables is also going to attempt deleting from jobs due to the FK from collectables to jobs. Having jobs in the cascade path twice is a problem.

I might be a little off on the specifics since you didn't include your schema, but the general principal should be correct.

lJohnson