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

Add root node to SQL CTE Hierarchy Tree

我有一个查询正在运行,它显示了我基于 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

其实,我觉得你只需要改变一下:

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

应该可以。