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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With