检索 SQL Server 2005 中的层次结构
Retrieving hierarchy in SQL Server 2005
我在数据库中有一个 table
EmployeeID TeamLeadID
2 1
3 2
4 3
5 NULL
1 NULL
6 1
7 2
8 3
现在我想要的是检索给定 EmployeeID
的所有 TeamLeadsID
(即所有上层)
对于 EmployeeID = 2
我应该得到答案 1(因为我们没有 TeamleadID
对于 EmployeeId = 1
)
对于 EmployeeID = 4
我应该得到 3,2 和 1(因为 4->Teamlead 是 3, 3 -> Teamlead 是 2, 2 -> TeamLead 是 1)
同样 EmployeeID = 7
我应该只得到 2 和 1
而对于 5 和 1,从 table 本身
可以清楚地看到它应该是 Null
最小工作量为:
- 转到 Google 并搜索 SQL 服务器递归 CTE 教程:https://www.google.com/search?q=sql+server+recursive+cte+tutorial
- 打开并阅读第一个 link:https://technet.microsoft.com/en-us/library/ms186243%28v=sql.105%29.aspx
编写如下查询:
Declare @EmployeeID int = 4
; with list(EmployeeID, TeamLeadID) as (
Select EmployeeID, TeamLeadID From Employees Where EmployeeID = @EmployeeID
Union All
Select e.EmployeeID, e.TeamLeadID From Employees E
Inner Join list l On l.TeamLeadID = E.EmployeeID
Where E.TeamLeadID is not NULL
)
Select TeamLeadID From list
我在数据库中有一个 table
EmployeeID TeamLeadID
2 1
3 2
4 3
5 NULL
1 NULL
6 1
7 2
8 3
现在我想要的是检索给定 EmployeeID
TeamLeadsID
(即所有上层)
对于
EmployeeID = 2
我应该得到答案 1(因为我们没有TeamleadID
对于EmployeeId = 1
)对于
EmployeeID = 4
我应该得到 3,2 和 1(因为 4->Teamlead 是 3, 3 -> Teamlead 是 2, 2 -> TeamLead 是 1)同样
EmployeeID = 7
我应该只得到 2 和 1
而对于 5 和 1,从 table 本身
可以清楚地看到它应该是 Null最小工作量为:
- 转到 Google 并搜索 SQL 服务器递归 CTE 教程:https://www.google.com/search?q=sql+server+recursive+cte+tutorial
- 打开并阅读第一个 link:https://technet.microsoft.com/en-us/library/ms186243%28v=sql.105%29.aspx
编写如下查询:
Declare @EmployeeID int = 4 ; with list(EmployeeID, TeamLeadID) as ( Select EmployeeID, TeamLeadID From Employees Where EmployeeID = @EmployeeID Union All Select e.EmployeeID, e.TeamLeadID From Employees E Inner Join list l On l.TeamLeadID = E.EmployeeID Where E.TeamLeadID is not NULL ) Select TeamLeadID From list