将根节点添加到SQL CTE层次结构树

时间:2015-12-30 19:58:25

标签: sql-server hierarchy common-table-expression

我有一个查询工作,显示基于CTE Recursion to get tree hierarchy的层次结构树。

结果看起来像

- Category
- Category
- - SubCategory
- - - Sub SubCategory
- - SubCategory
...

我想在我的树中添加一个根节点,但我还没有看到如何做到这一点。如何将根节点添加到此树?

编辑:我当前的查询如下:

;WITH Tree as
(
    Select Parent_ID, ParentDescr, Node_ID, Node, 1 as Level, cast(Node as varchar(max)) as Path
    FROM Nodes
    WHERE ParentDescr = 'Root'

    UNION ALL

    Select  A.Parent_ID, A.ParentDescr, A.Node_ID, A.Node, Level + 1 as Level, cast(B.Path + ' | ' + A.Node as varchar(max)) as Path
    FROM Nodes A
    INNER JOIN Tree B ON A.PARENT_ID = B.Node_ID
    WHERE A.ParentDescr <> 'Root'
) 
SELECT  REPLICATE(' - ', level) + Node as Tree, Path, Node_ID, ParentDescr, PARENT_ID
from Tree
ORDER BY Path asc

以下是一些示例数据:

SELECT * 
FROM (
VALUES 
('123','Root',NULL,NULL),
('456','Category','123','Root'),
('789','SubCategory','456','Category'),
('012','Sub SubCategory','789','SubCategory'),
('345','Category','123','Root')) AS vtable 
([Class_ID],[Class],[Parent_ID],[ParentClass])

结果应该如下:

Root
- Category
- - SubCategory
- - - Sub SubCategory
- Category

1 个答案:

答案 0 :(得分:0)

实际上,我认为你只需要改变这个:

WHERE ParentDescr = 'Root'

对此:

WHERE Node = 'Root'

同样,改变这个:

WHERE A.ParentDescr <> 'Root'

对此:

WHERE A.Node <> 'Root'

编辑:

根据您的示例数据,如果您正确实施了这些更改,我的更改应该会有效。验证您的新查询如下所示:

;WITH Tree as
(
    Select Parent_ID, ParentDescr, Node_ID, Node, 1 as Level, cast(Node as varchar(max)) as Path
    FROM Nodes
    WHERE Node = 'Root'

    UNION ALL

    Select  A.Parent_ID, A.ParentDescr, A.Node_ID, A.Node, Level + 1 as Level, cast(B.Path + ' | ' + A.Node as varchar(max)) as Path
    FROM Nodes A
    INNER JOIN Tree B ON A.PARENT_ID = B.Node_ID
    WHERE A.Node <> 'Root'  --this line really isn't even necessary
) 
SELECT  REPLICATE(' - ', level) + Node as Tree, Path, Node_ID, ParentDescr, PARENT_ID
from Tree
ORDER BY Path asc

它应该有用。