需要从递归表生成视图

时间:2017-10-28 08:21:45

标签: c# sql recursive-query

如果有人可以提供帮助,我会陷入困境:  我的桌子看起来如下 A table in my data base

请注意:可以有n个级别,但如果您在某个级别添加项目,则无法创建子级别。

从上面我想要产生这种观点:

The view i want to generate from the above table

即使它可能在c#中请指出。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

应该如此简单:

CREATE VIEW YourViewName
AS
    WITH Tree (ID, [NAME], PARENT_ID, Depth, Sort) AS
    (
        SELECT ID, [NAME], PARENT_ID, 0 AS Depth, CONVERT(varchar(255), [Name]) AS Sort         
        FROM Category
        WHERE PARENT_ID = 0
        UNION ALL
        SELECT CT.ID, CT.[NAME], CT.PARENT_ID, Parent.Depth + 1 AS Depth, 
        CONVERT(varchar(255), Parent.Sort + ' | ' + CT.[NAME]) AS Sort
        FROM Category CT
        INNER JOIN Tree as Parent ON Parent.ID = CT.PARENT_ID
    )

    -- HERE IS YOUR TREE, Depths gives you the level starting with 0 and Sort is the Name based path
    SELECT ID, [NAME], PARENT_ID, Depth, Sort FROM Tree
GO

答案 1 :(得分:1)

我喜欢递归节目

fanout

enter image description here