确定员工经理的完整层次结构的查询是什么?
示例:Alex是输入
Sara(经理 - 1级) 詹姆斯(经理 - 二级) 大卫(经理 - 3级) 亚历克斯(简单员工)
答案 0 :(得分:0)
DECLARE @Hierarchy TABLE (
ID int,
Manager int,
Level int);
WITH Hierarchy(ID, Manager, Level) AS (
SELECT EmployeeID, ManagerID, 0
FROM HumanResources.Employee
JOIN Person.Contact
ON Contact.ContactID = Employee.ContactID
WHERE FirstName = N'Alex'
UNION ALL
SELECT EmployeeID, ManagerID, Level + 1
FROM HumanResources.Employee
JOIN Hierarchy
ON Manager = EmployeeID)
INSERT @Hierarchy
SELECT *
FROM Hierarchy
DECLARE @HighestLevel int
SELECT @HighestLevel = MAX(Level)
FROM @Hierarchy
DECLARE Hierarchy CURSOR FOR
SELECT
FirstName +
N'(' +
CASE
WHEN Level = 0
THEN N'Simple Employee'
ELSE
N'Manager - Level ' +
CAST(@HighestLevel - Level + 1 AS varchar) END +
N')'
FROM HumanResources.Employee
JOIN @Hierarchy
ON ID = EmployeeID
JOIN Person.Contact
ON Contact.ContactID = Employee.ContactID
ORDER BY Level DESC
DECLARE @Employee nvarchar(max)
DECLARE @Result nvarchar(max)
SET @Result = N''
OPEN Hierarchy
FETCH Hierarchy
INTO @Employee
WHILE @@FETCH_STATUS = 0 BEGIN
SET @Result = @Result + N' ' + @Employee
FETCH Hierarchy INTO @Employee
END
CLOSE Hierarchy
DEALLOCATE Hierarchy
PRINT @Result