views:

32

answers:

1

I have this table with pages, these pages have parents that are also pages in the same table.

For this examples sake the table looks like:

table: Pages
PageId :Key
PageParent :Foreign Key
PageName

Now my question is what would the SQL look like when creating a menustructure like:

PageId     PageParent     PageName
1          NULL           home
 2          1              page_under_home1
  5          2              page_under_pageid2_1
  6          2              page_under_pageid2_2
 4          1              page_under_home2
  5          4              page_under_pageid4_1
   7          5              page_under_pageid5_1
  6          4              page_under_pageid4_2
   9          6              page_under_pageid6_1
   10         6              page_under_pageid6_2
 8          1              page_under_home3
 11         1              page_under_home4
  12         11             page_under_pageid11_1
   13         12             page_under_pageid12_1

I currently have this:

SELECT     p1.PageId, p1.PageName, p1.PageParent, p2.PageName AS Expr1
FROM         dbo.pages AS p1 FULL OUTER JOIN
                          (SELECT     PageId, PageName
                            FROM          dbo.pages
                            WHERE      (PageParent IS NULL)) AS p2 ON p2.PageId = p1.PageParent

but that doesnt nearly create the output I want and I think I'm going at it completely the wrong way...

EDIT:

this is what I currently have:

WITH 
    PagesMenu(pageId, PageParent, PageName) 
AS 
(
    SELECT     
        PageId, PageParent, PageName
    FROM         
        dbo.pages
    WHERE     
        (PageParent IS NULL) 
        AND 
        (PageIsVisible = 'True')
    UNION ALL

    SELECT     
        b.PageId, b.PageParent, b.PageName
    FROM         
        PagesMenu AS a 
    INNER JOIN
        dbo.pages AS b 
    ON 
        a.pageId = b.PageParent
)

SELECT     pageId, PageParent, PageName
FROM         PagesMenu

And it seems to somewhat work but not completely recurs, the first recursion seems to work but it looks like it doesn't do it a second time.

Result:

pageId    PageParent    PageName
3         NULL          home
1         3             test
4         3             test
5         4             test
6         4             test
7         4             test
8         5             test  <---wrong
2         1             test  <---wrong
A: 

Here is an MS link on CTE's: http://msdn.microsoft.com/en-us/library/ms186243.aspx

spinon