-
Notifications
You must be signed in to change notification settings - Fork 1
Home
I'm facing a database with circular references and was wondering if I could detect them by script. The presented solution is for MS SQL Server, but I think it can be adapted easily for other RDBMS as long as they support recursive CTE.
This is a circular reference:
There are 2 paths from ProjectAssignment to Project, leading to potentially different results!
- ProjectAssignment -> Task -> Project
- ProjectAssignment -> ProjectTeam -> Project
There are 3 types of circular references that come to my mind:
- True circles, endless loop: A -> B -> C -> A
- Self-references, parent-child
- Multi-table circular-references
Welcome to a chicken-egg situation and good luck entering data! These will be detected soon, so let's not worry about them.
These are unproblematic. If parent=null marks root nodes, then just add a check-constraint to ensure that the parent-id is not the child-id itself.
These are the ones that we want to detect!
Here's another example:

What identifies such circular references?
One element of such circles is a table, whose primary key is referenced by more then one other table.
On the other side of the circle is a table with FK references to more then one table.
These 2 tables are by more then one path
So the question is: can we find such circular references by script? Let's try ..