sql recursive function - to find managers

2019-04-08 19:11发布

问题:

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.

回答1:

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')


回答2:

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