Search code examples
t-sqlforeign-keyscross-join

Way to check for recursive foreign keys


Say I have a table named EMPLOYEE, and the table has a field called ManagerID. This field is a FK to another record of the EMPLOYEE table of who their manager is. What is an ideal way to verify that there is no circular reference (recursive foreign keys)?

EDIT - Let me add that every employee does NOT need a manager. There will be some employee records that do not have their ManagerID field set.

*Example: User 123 has User 345 as their manager. User 345 has User 567 as their manager. For some crazy reason, User 567 has User 123 as their manager.

I want to check if User 345 is in a circular reference.*

What is the best way to figure this out? A simple query? Business logic code (C#/VB.NET)?

What have other people done?

Example table schema -

-- Employee Table --
UserID (int - PK)
ManagerID (int - FK to another UserID; can be null)

Solution

  • Here's a few starters - they either use recursive CTEs or cursors:

    http://blogs.msdn.com/b/sqlazure/archive/2010/07/01/10033575.aspx

    http://social.msdn.microsoft.com/Forums/en-ZA/transactsql/thread/50a0bd26-87c8-4197-84f9-5fb1dfd792b6