0

确定员工经理的完整层次结构的查询是什么?

示例:Alex 是输入

Sara(经理 - 1 级) James(经理 - 2 级) David(经理 - 3 级) Alex(简单员工)

4

1 回答 1

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
于 2010-10-30T14:58:20.653 回答