Recursive sql function - find managers

Let's 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 out all the managers as user_id, which you are looking for. So, for example, if I send to Linda, then it should return me:

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

or if I send to Mark, then he should return me:

Steve

I heard about a recursive function, but I'm not sure how to do it. Any help would be greatly appreciated.

+5
source share
2 answers

Using:

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

Scenarios:

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')
+6
source

MSDN .

0

All Articles