0

我有MenuItem以下格式的 SQL Server 2008 表。

 MenuItemsID     MenuType     ItemsName  ParentID     URL          Images

       1            1           Home         0         --            ---
       2            1          Product       0         ---           ----
       3            1          Catagories    0         ---            ----
       4            1          Brand         0         Brand.aspx     ----
       5            1          H1            1         ------          -----
       6            1          H2            1         ------        --------
       7            1          P1            2         ----           ------
       8            1          c1            3         ----           ---
       9            1          H1Submneu1    5         ---               ----
       10           1           P1 subMenu   7         -------           ---

像那样

我试图编写一个查询来检索最多一级子菜单

select 
    m.ItemName, STUFF((select ',' + s.ItemName 
                       from MenuItems s
                       where s.ParentId = m.MenuItemsID FOR XML PATH('')), 1, 1, '') as SubMenus
from MenuItems m 
where ParentId = 0

但我想要 m 个级别的子菜单

如何编写该查询?谁能帮帮我吗?

4

2 回答 2

2

您需要一个递归 CTE(公用表表达式)来实现这一点。尝试这样的事情:

;WITH Submenus AS
(
    SELECT 
        MenuItemID, ItemsName, ParentID, Level = 0
    FROM
        dbo.menuitem m
    WHERE
        m.ParentID = 0

    UNION ALL

    SELECT 
        m2.MenuItemID, m2.ItemsName, m2.ParentID, s.Level + 1 
    FROM
        dbo.menuitem m2
    INNER JOIN
        Submenus s ON m2.ParentID = s.MenuItemID  
)  
SELECT
    *
FROM    
    Submenus
ORDER BY
    Level, MenuItemID

这给了我一个输出:

MenuItemID  ItemsName  ParentID  Level
   1        Home           0       0
   2        Product        0       0
   3        Categories     0       0
   4        Brand          0       0
   5        H1             1       1
   6        H2             1       1
   7        P1             2       1
   8        C1             3       1
   9        H1Sub1         5       2
  10        P1Sub1         7       2
于 2012-10-05T11:02:10.393 回答
0

您可以使用递归 CTE:

;WITH cte_menu(Level, MenuItemsId, MenuType, ItemsName, ParentID, URL, Images)
AS
(
SELECT 0 AS Level, MenuItemsId, MenuType, ItemsName, ParentID, URL, Images
FROM MenuItem 
WHERE ParentID = 0

UNION ALL

SELECT Level + 1, t.MenuItemsId, t.MenuType, t.ItemsName, t.ParentID, t.URL, t.Images
FROM MenuItem  t
INNER JOIN cte_menu c ON c.MenuItemsId = t.ParentID
)
SELECT *
FROM cte_menu
ORDER BY Level, MenuItemsId

更多关于使用 CTE 的递归查询

于 2012-10-05T11:01:05.247 回答