-
Notifications
You must be signed in to change notification settings - Fork 1
Home
This is a circular reference:
There are 2 paths from ProjectAssignment to Project, leading to potentially different results!
- ProjectAssignment -> Task -> Project
- ProjectAssignment -> ProjectTeam -> Project
- Run the script SQL-Find-Circular-References/src/main/sql/findCircularReferences.sql
- You should get a list of circular references like this: source | target | path --- | --- | --- dbo.Project | dbo.ProjectAssignment | dbo.Project>dbo.ProjectTeam>dbo.ProjectAssignment dbo.Project | dbo.ProjectAssignment | dbo.Project>dbo.Task>dbo.ProjectAssignment
- Modify part 1 in the script. Write a query which lists all PK-FK relations in your DB.
- Change the few SQL Server specific things like datatypes
- Run your script
- Send me a pull-request!!! :-)
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.
There is more then one path from the first to the second table.
So the question is: can we find such circular references by script? Let's try ..
- List all PK-FK relations
- Find PKs that are referenced more then once (reduces workload for next step)
- Find all possible paths from those PK tables to any other table (using recursive CTE)
- Identify problematic circles
- Display result nicely as paths
For SQL Server:
test test