我有以下格式的SQL Server 2008表MenuItem
。
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
但我想要多级别的子课程
怎么写这个查询?有人可以帮帮我吗?
答案 0 :(得分: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
答案 1 :(得分: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