sql recursive function - to find managers

浪子不回头ぞ 提交于 2019-12-06 03:17:37

问题


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.



来源:https://stackoverflow.com/questions/3859882/sql-recursive-function-to-find-managers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!