|Back to Papers and Articles
Using SQL Server 2000's User Defined Function to solve the Tree Problem
Copyright 2001 Paragon Corporation ( April 16, 2001)
Tree problems have plagued SQL Server db programmers for a long time. The new user defined function feature in SQL Server 2000 provides a relief to this dilemma. In this article we demonstrate an approach to solving the employee supervisor tree problem using a recursive user-defined SQL Server 2000 function call.
The Problem Suppose you have an employee called John and John directly reports Nancy. Nancy directly reports to Peter and Peter directly reports to Diana. The table you have set up to model this relationship has two fields for simplicity EmployeeID varchar(50), ManagerID varchar(50). In your table are the following entries
Now John is a very insecure person and knows he is way down on the food chain. He requests a report from you that gives him a synopsis of where he stands in the food chain of the company to figure out how far he needs to climb.
You think about it for a minute and come up with this recursive function that given a person's employee id will provide a list of all his direct and indirect supervisors ordered by rank. The function looks as follows
To figure out who John's supervisors are in order of rank you perform the following select statement
SELECT * From reportsTo('John',0) order by depth DESC
Diana 2 Peter 1 Nancy 0
Back to Papers and Articles