I am writing a stored procedure for retrieving the xml structure for a menu control. This seems to be a valid code( according to me & it is wrong) but does not run well on query tester. How could i correct it of the error below is the code
;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]
Where ParentMenuId and MenuId are related. Certain other doubts i got are below
- Is this perfectly fine to use
CTEfor menu. What other types have you been successful DataSetandChildRelationsare good too(or maybe i am wrong) for this purpose ?
Give me more ideas on how you have accomplished menu system in your projects.
Input
MenuId MenuName ApplicationId ParentMenuId
1 MenuName1 1 -1
2 MenuName2 1 1
3 MenuName3 1 -1
4 MenuName4 1 2
Output
<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>
Don’t mind about the xml structure i is easy to get with FOR XML PATH i am not getting the query to run in the first place.
I’d wager that
should in fact be
edit
Using this sample data:
and your query, with the above modification, I get
which looks correct. To help you we need to see all your relevant code.