【问题标题】:Generate breadcrumb from database in asp.net从 asp.net 中的数据库生成面包屑
【发布时间】:2014-08-31 07:53:36
【问题描述】:

我需要为基于pageID 的任何页面生成面包屑。下面是基于 MS Sql 服务器的示例数据示例sql script

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

INSERT INTO PageMenu
    ([PageId], [PageName], [path], [PageInheritance])
VALUES
    (1, 'Home', '/en/', 0),
    (2, 'About Us', '/en/about-us/', 0),
    (3, 'Our Mission', '/en/about-us/our-mission/', 2),
    (4, 'Our Vision', '/en/about-us/our-vision/', 2),
    (5, 'Media', '/en/media/', 0),
    (6, 'Press Release', '/en/media/press-releases/', 5),
    (7, 'Video Gallery', '/en/media/video-gallery/', 5),
    (8, 'Products', '/en/products/', 0),
    (9, 'Mens', '/en/products/mens/', 8),
    (10, 'Womens', '/en/products/womens/', 8),
    (11, 'Footwear', '/en/products/footwear/', 9),
    (12, 'Footwear', '/en/products/footwear/', 10),
    (13, 'Shoes', '/en/products/mens/footwear/shoes/', 9),
    (14, 'Sandals', '/en/products/mens/footwear/sandals/', 9),
    (15, 'Kids', '/en/products/kids/', 8)
;

我想创建一个基于 CTE 的存储过程,我想传递 pageid 并且它应该以面包屑的形式递归返回页面路径

假设如果我通过并且pageid=11 那么它应该以以下格式返回我以下行

pageid_____PageName________Path
1          Home            /en/
8          Products        /en/products/
9          Mens            /en/products/mens/
11         Footwear        /en/products/mens/footwear/

根据上面的结果集,我可以生成如下面包屑

Home > Products > Mens > Footwear

【问题讨论】:

  • “我试图在 sql fiddle 上设置它,但失败并出现一些错误。” - 这真的很有帮助.....
  • 第 8 行继承自 1 而不是 0。
  • @HamletHakobyan,实际上0 是用于根级菜单的所有菜单,如Home,Products, About us, Media,其PageInheritance 为0。这就是它在我的数据库中的实际情况。
  • @KnowledgeSeeker 仔细看看。正如您所说,菜单产品位于根目录中。我不这么认为。家是你的根吗?还是在根目录下?
  • 请将您的解决方案添加为答案,而不是将其合并到您的问题中。

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


【解决方案1】:

这是我找到的解决方案:

;WITH RecursiveTable (PageId, PageName,  Path, PageInheritance, Level)
AS(
   --Anchor
    SELECT      tt.PageId,  tt.PageName, tt.Path, tt.PageInheritance,  0 AS Level
    FROM pg_Menu AS tt
    WHERE PageId = 13
    UNION ALL
   --Recursion
    SELECT tt.PageId,  tt.PageName,  tt.Path, tt.PageInheritance, Level + 1
    FROM pg_Menu AS tt
    INNER JOIN RecursiveTable rt ON rt.PageInheritance = tt.PageId
)
SELECT * FROM RecursiveTable ORDER BY Level DESC

PageID = 13的结果

pageid_____PageName________Path
8          Products        /en/products/
9          Mens            /en/products/mens/
11         Footwear        /en/products/mens/footwear/
13         Shoes           /en/products/mens/footwear/shoes/

更新:小提琴示例http://sqlfiddle.com/#!3/e4ce3/2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2012-12-04
    • 1970-01-01
    相关资源
    最近更新 更多