views:

35

answers:

2

Lets say I have the following table

User_ID  Manager_ID  
---------------------
Linda        Jacob  
Mark         Linda  
Kevin        Linda  
Steve        Mark  
John         Kevin

Basically the requirement is to pull all the managers under the user_id you are searching for. So for instance if I send in 'Linda' then it should return me:

'Mark', 'Kevin', 'Steve', 'John'  

or if I send in 'Mark' then it should return me:

Steve

I have heard of recursive function but I am unsure of how to do this. Any help would be appreciated.

A: 

The code example from Recursive Queries Using Common Table Expressions on MSDN shows exactly that.

GSerg
+1  A: 

Use:

WITH hieararchy AS (
   SELECT t.user_id
     FROM YOUR_TABLE t
    WHERE t.manager_id = 'Linda'
   UNION ALL
   SELECT t.user_id
     FROM YOUR_TABLE t
     JOIN hierarchy h ON h.user_id = t.manager_id)
SELECT x.*
  FROM hierarchy x

Resultset:

user_id
--------
Mark
Kevin
John
Steve

Scripts:

CREATE TABLE [dbo].[YOUR_TABLE](
 [user_id] [varchar](50) NOT NULL,
 [manager_id] [varchar](50) NOT NULL
)

INSERT INTO YOUR_TABLE VALUES ('Linda','Jacob')
INSERT INTO YOUR_TABLE VALUES ('Mark','Linda')
INSERT INTO YOUR_TABLE VALUES ('Kevin','Linda')
INSERT INTO YOUR_TABLE VALUES ('Steve','Mark')
INSERT INTO YOUR_TABLE VALUES ('John','Kevin')
OMG Ponies
Thanks this works perfectly, quick question. Is there anyway to put the results in a an array so I can use it within my select statement
Jacob
@Jacob: You can join to the name of the CTE, like you would for any table or view
OMG Ponies