递归CTE查询生成产品或页面层次结构

时间:2014-02-10 07:23:06

标签: sql sql-server sql-server-2008

Page_ID     Page_Name               Page_Title              Page_Handler        Parent_Page_ID  Language_ID     Region_ID
1           Home                    Home                    index.aspx              0               1               uae
2           Personal                Personal                index.aspx              0               1               uae
3           Accounts & Deposits     Accounts & Deposits     index.aspx              2               1               uae
4           Current Account         Current Account         current-account.aspx    3               1               uae
5           Current Gold Accounts   gold Account            gold-account.aspx       3               1               uae
6           Easy Saver              Easy Saver Account      saver-account.aspx      3               1               uae
7           Fixed Deposits          Fixed Account           fixed-account.aspx      3               1               uae
8           Loans                   Loans                   index.aspx              2               1               uae
9           Personal Loans          Personal Loans          index.aspx              8               1               uae
10          car Loans               car Loans               car-loan.aspx           8               1               uae

我想为asp.net路由生成以下路径,我也可以使用相同的面包屑导航

www.abc.com/home
www.abc.com/personal
www.abc.com/personal/acounts-deposits/
www.abc.com/personal/acounts-deposits/current-account
www.abc.com/personal/acounts-deposits/current-gold-account
www.abc.com/personal/acounts-deposits/easy-saver
......
......
www.abc.com/personal/loans/
www.abc.com/personal/loans/personal-loans
www.abc.com/personal/loans/car-loans

我修改了一个CTE脚本来处理我的表的类似结构。但是这个CTE的问题在于它给我sibling/child/parent ...而我需要路径为parent/child/sibling

示例http://sqlfiddle.com/#!3/0d086/1

示例代码 - 由于sqlfiddle的限制,我使用了短数据

CREATE TABLE PageMenu
    ([PageId] int, [PageName] varchar(5), [PageInheritance] int)
;

INSERT INTO PageMenu
    ([PageId], [PageName], [PageInheritance])
VALUES
    (1, 'home', 0),
    (2, 'p1', 0),
    (3, 'c1', 2),
    (4, 'c2', 2),
    (5, 's3', 4),
    (6, 'S3a', 5)
;
WITH CategoryCTE AS
(   SELECT  PageId, 
            PageName, 
            PageInheritance, 
            RecursionLevel = 1, 
            ParentRoot = CAST('None' AS VARCHAR(MAX)),
            LastParentCatID = PageInheritance
    FROM    PageMenu
    UNION ALL
    SELECT  cte.PageId, 
            cte.PageName,
            cte.PageInheritance,
            cte.RecursionLevel + 1,
            ParentRoot = CASE WHEN cte.RecursionLevel = 1 THEN '' ELSE cte.ParentRoot + '/' END + c.PageName,
            LastParentCatID = c.PageInheritance
    FROM    CategoryCTE cte
            INNER JOIN PageMenu c
                ON c.PageId = cte.LastParentCatID
), MaxRecursion AS
(   SELECT  PageId, 
            PageName, 
            PageInheritance, 
            ParentRoot, 
            RowNum = ROW_NUMBER() OVER(PARTITION BY PageId ORDER BY RecursionLevel DESC)
    FROM    CategoryCTE
)
SELECT  PageId, PageName, PageInheritance, ParentRoot
FROM    MaxRecursion
WHERE   RowNum = 1 ORDER BY PageId DESC;

2 个答案:

答案 0 :(得分:1)

如果我理解正确,这将是我解决这个问题的方法。它可能不是完整的答案,但它会让你在某个地方接近。

;with cte 
as (
    select
        t.PageInheritance, 1 as Level,
        CASE WHEN cast(t.PageInheritance as nvarchar(max)) <> N'0' 
       THEN cast(t.PageInheritance as nvarchar(max)) + '/' + cast(t.PageId as nvarchar(max)) 
  ELSE cast(t.PageId as nvarchar(max)) END AS [Path]
    from PageMenu as t

    union all

    select
        t.PageInheritance, Level + 1 as Level,
        CASE WHEN cast(t.PageInheritance as nvarchar(max)) <> N'0' 
      THEN cast(t.PageInheritance as nvarchar(max)) + '/' + c.[Path] 
        ELSE c.[Path] END as [Path] 
    from PageMenu as t
        inner join cte as c on c.PageInheritance = t.PageId
)
select 'www.abc.com/'+[Path] AS [Paths]
from cte 
WHERE PageInheritance = 0
order by [Level] ASC

结果集

╔═════════════════════╗
║        Paths        ║
╠═════════════════════╣
║ www.abc.com/1       ║
║ www.abc.com/2       ║
║ www.abc.com/2/4     ║
║ www.abc.com/2/3     ║
║ www.abc.com/2/4/5   ║
║ www.abc.com/2/4/5/6 ║
╚═════════════════════╝

答案 1 :(得分:1)

我认为M. Ali(在评论中做出更正)比你的方法更合适。无论如何,如果你只想纠正你的查询,就像从递归查询中改变ParentRoot计算一样简单:

ParentRoot = CASE WHEN cte.ParentRoot <> 'None' THEN c.PageName + '/' + cte.ParentRoot ELSE c.PageName END,

因此,您的查询将如下所示:

    WITH CategoryCTE AS
(   SELECT  PageId, 
            PageName, 
            PageInheritance, 
            RecursionLevel = 1, 
            ParentRoot = CAST('None' AS VARCHAR(MAX)),
            LastParentCatID = PageInheritance
    FROM    PageMenu
    UNION ALL
    SELECT  cte.PageId, 
            cte.PageName,
            cte.PageInheritance,
            cte.RecursionLevel + 1,
            ParentRoot = CASE WHEN cte.ParentRoot <> 'None' THEN c.PageName + '/' + cte.ParentRoot ELSE c.PageName END,
            LastParentCatID = c.PageInheritance
    FROM    CategoryCTE cte
            INNER JOIN PageMenu c
                ON c.PageId = cte.LastParentCatID
), MaxRecursion AS
(   SELECT  PageId, 
            PageName, 
            PageInheritance, 
            ParentRoot, 
            RowNum = ROW_NUMBER() OVER(PARTITION BY PageId ORDER BY RecursionLevel DESC)
    FROM    CategoryCTE
)
SELECT  PageId, PageName, PageInheritance, ParentRoot
FROM    MaxRecursion
WHERE   RowNum = 1 
ORDER BY PageId DESC;

更新:这是阿里的答案更正,以显示作为问题的作者想要的结果,甚至简化:

;with cte 
as (
    select
    t.PageInheritance, 1 as Level, 
    cast(t.Pagename as nvarchar(max)) AS [Path]
    from PageMenu as t

    union all

    select
    t.PageInheritance, Level + 1 as Level,
    cast(t.PageName as nvarchar(max)) + '/' + c.[Path] as [Path] 
    from PageMenu as t  
    inner join cte as c on c.PageInheritance = t.PageId
)
select N'www.abc.com/' + [Path] AS [Paths]
from cte 
WHERE PageInheritance = 0
order by [Level] ASC