2014-08-31 20 views
-2

我需要爲基於pageID的任何頁面生成麪包屑。以下是基於MS Sql服務器的示例數據示例sql script從asp.net中的數據庫生成麪包屑

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) 
; 

我想創建,我想通過pageid基於CTE存儲過程,它應該遞歸返回頁面的路徑在麪包屑的形式

想,如果我通過和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

+0

「我試着將它設置在SQL擺弄它失敗了,所以我錯了。「 - 這真的有幫助..... – 2014-08-31 08:01:42

+0

第8行從1繼承,而不是從0繼承。 – 2014-08-31 08:09:50

+0

@HamletHakobyan,實際上'0'是用於根級菜單的所有菜單,比如'Home,Products,About us,Media',PageInheritance爲0這就是它在我的數據庫中的實際情況。 – Learning 2014-08-31 08:21:30

回答

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