1

可能重复:
使用 CTE 进行真正的递归?

给定一个引用自身的分层表,例如具有以下列的 Employee 表:

Table      Employee
    Column Id INT NOT NULL
    Column ParentId INT NOT NULL (references Id)
    Column Name NVARCHAR(60) NOT NULL

以下查询将为我提供基于给定 EmployeeId 的所有记录:

DECLARE @EmployeeId INT = <%insert EmployeeId here%>;

WITH CDE AS
(
    SELECT
        *,
        0 AS Level
    FROM
        collaboration.Employee AS E
    WHERE
        Id = @EmployeeId
    UNION ALL
    SELECT
        E.*,
        CDE.Level + 1 AS Level
    FROM
        collaboration.Employee AS E
        INNER JOIN
        CDE ON E.ParentId = CDE.Id AND E.Id <> 0
)
SELECT DISTINCT
    CDE.*
FROM
    CDE
ORDER BY
    CDE.Level

如果有意义的话,我想要的是能够按“分支”然后“级别”进行排序。所以给出下表:

1    0    John Smith
2    1    John Doe
3    1    Jane Williams
4    2    Ian Bond
5    2    James Fleming

我希望结果看起来像:

1    0    John Smith
2    1    John Doe
4    2    Ian Bond
5    2    James Fleming
3    1    Jane Williams

我想要一个不涉及构建字符串以方便排序的解决方案。如果无法解决,我想知道原因。

4

1 回答 1

2
;WITH CDE AS 
( 
    SELECT 
        *, 
        0 AS Level,
        convert(nvarchar(50),id) as EPath
    FROM 
        collaboration.Employee AS E 
    WHERE 
        Id = @EmployeeId 
    UNION ALL 
    SELECT 
        E.*, 
        CDE.Level + 1 AS Level ,
        convert(nvarchar(50),Epath+'/'+CONVERT(nvarchar(5),e.id))
    FROM 
        collaboration.Employee AS E 
        INNER JOIN 
        CDE ON E.ParentId = CDE.Id AND E.Id <> 0 
) 
SELECT DISTINCT 
    CDE.* 
FROM 
    CDE 
ORDER BY 
    EPath

By the way, SQL Server 2008 has a HierarchyID data type for just this kind of thing.

于 2012-08-31T11:38:09.317 回答