2008-10-02 51 views
3

我有一個SQL Server 2005的表是這樣的:TSQL:如何在XML中進行自連接以獲取嵌套文檔?

create table Taxonomy(
CategoryId integer primary key, 
ParentCategoryId integer references Taxonomy(CategoryId), 
CategoryDescription varchar(50) 
) 

數據看上去就像 CategoryIdParentCategoryIdCategoryDe​​scription 123nullfoo345123bar

我想它查詢到這樣一個XML文檔:

<taxonomy> 
<category categoryid="123" categorydescription="foo"> 
     <category id="455" categorydescription="bar"/> 
</category> 
</taxonomy> 

是否可以這樣做使用FOR XML AUTO,ELEMENTS?或者我需要使用FOR XML EXPLICIT?

回答

3

這是可能的,但主要限制是層次的級別必須硬編碼。 SQL Server聯機叢書描述瞭如何用this link表示XML中的層次結構。以下是生成您請求的XML的示例查詢:

SELECT [CategoryId] as "@CategoryID" 
     ,[CategoryDescription] as "@CategoryDescription" 
     ,(SELECT [CategoryId] 
     ,[CategoryDescription] 
     FROM [dbo].[Taxonomy] "Category" 
     WHERE ParentCategoryId = rootQuery.CategoryId 
     FOR XML AUTO, TYPE) 
FROM [dbo].[Taxonomy] as rootQuery 
where [ParentCategoryId] is null 
FOR XML PATH('Category'), ROOT('Taxonomy')