我正在编写一个存储过程,用于检索菜单控件的xml结构。这段代码看起来是有效的(至少我认为是有效的),但在查询测试器上运行不良。如何更正它?以下是代码:
;WITH Hierarchy AS
(
SELECT
MenUid,MenuName,ApplicationId,ParentMenuId, 1 AS 'Level'
FROM
dbo.Menu
WHERE
ParentMenuId = '-1'
UNION ALL
SELECT
M.MenUid,M.MenuName,M.ApplicationId,M.ParentMenuId, Level + 1 AS 'Level'
FROM
dbo.Menu M
INNER JOIN
Hierarchy h ON M.ParentMenuId = h.MenuId
)
SELECT *
FROM Hierarchy
ORDER BY [Level],[MenuName]
ParentMenuId和MenuId相关联。我还有一些疑问如下:
- 使用CTE来处理菜单是否完全可行?您还成功使用过哪些其他类型?
DataSet
和ChildRelations
对于这个目的也不错(或者我错了)?
请给我更多关于如何在您的项目中实现菜单系统的想法。
输入
MenuId MenuName ApplicationId ParentMenuId
1 MenuName1 1 -1
2 MenuName2 1 1
3 MenuName3 1 -1
4 MenuName4 1 2
输出
<Output>
<Menu>
<MenuId>1</MenuId>
<MenuName>MenuName1</MenuName>
<ApplicationId>1</ApplicationId>
<ParentMenuId>-1</ParentMenuId>
<SubMenu>
<Menu>
<MenuId>2</MenuId>
<MenuName>MenuName2</MenuName>
<ApplicationId>1</ApplicationId>
<ParentMenuId>1</ParentMenuId>
<SubMenu>
<MenuId>3</MenuId>
<MenuName>MenuName4</MenuName>
<ApplicationId>1</ApplicationId>
<ParentMenuId>3</ParentMenuId>
</SubMenu>
</Menu>
</SubMenu>
</Menu>
<Menu>
<MenuId>4</MenuId>
<MenuName>MenuName3</MenuName>
<ApplicationId>1</ApplicationId>
<ParentMenuId>-1</ParentMenuId>
</Menu>
</Output>
不要担心XML结构,使用FOR XML PATH
很容易获取它,但我首先无法运行查询。