Problem 2 is that I need to format all of this as heirarchal xml but when I output it as xml in the query itself, every element is coming through as MainTabs (the cte name) instead of nesting rows 3,4 & 5 under tab id 4. So, how do I (if it's even possible) fix these two things? If I can't do this in a query, how would you suggest getting an xml formatted result set from a table structure like this? Structure meaning parenttabid = tabid of another row ordered by the tabid and then tabindex? Thanks.
with MainTabs(ParentTabId, TabId, Title, Link, tabindex) as
(
select ParentTabId, TabId, Title, Link, tabindex from Tabs where parenttabid = 1
UNION ALL
select t.ParentTabId, t.TabId, t.Title, t.Link, t.tabindex from Tabs t inner join
MainTabs on MainTabs.TabId = t.ParentTabId
)
select ParentTabId, TabId, Title, Link, tabindex from MainTabs order by tabid, tabindex
You can generate hierarchical XML using this
CREATE FUNCTION dbo.SubTree(@.TabId int)
RETURNS XML
WITH RETURNS NULL ON NULL INPUT
BEGIN RETURN
(SELECT ParentTabId as "@.ParentTabId",
TabId as "@.TabId",
Title as "@.Title",
Link as "@.Link",
tabindex as "@.tabindex",
dbo.SubTree(TabId)
FROM Tabs
WHERE ParentTabId=@.TabId
ORDER BY TabId
FOR XML PATH('Tabs'),TYPE)
END
GO
SELECT ParentTabId as "@.ParentTabId",
TabId as "@.TabId",
Title as "@.Title",
Link as "@.Link",
tabindex as "@.tabindex",
dbo.SubTree(TabId)
FROM Tabs
WHERE parenttabid = 1
ORDER BY TabId
FOR XML PATH('Tabs') , ROOT('MyRoot'), TYPE
|||
SQL Server 2005 has a maximum limit of 32 recursively nested function invocations. If your parts hierarchy exceeds the limit, you will need to use the old approach of getting the XML in flat form and applying an XSLT style sheet to create the hierarchy.
Its mentioned here : http://msdn2.microsoft.com/en-us/library/ms345137.aspx
Can you suggest any alternate option?
No comments:
Post a Comment