2008-10-02 7 views
3

J'ai une table SQL Server 2005 comme ceci:TSQL: Comment faire une auto-jointure en XML pour obtenir un document imbriqué?

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

avec des données ressemblant à CategoryIdParentCategoryIdCategoryDescription 123nullfoo345123bar

Je voudrais l'interroger dans un document XML comme ceci:

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

Est-ce possible? avec FOR XML AUTO, ELEMENTS? Ou dois-je utiliser FOR XML EXPLICIT?

Répondre

3

C'est possible mais la principale limitation est que les niveaux de la hiérarchie doivent être codés en dur. La documentation en ligne de SQL Server a une description de la façon de représenter les hiérarchies en XML au this link. Voici un exemple de requête qui produit le fichier XML demandé:

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') 
Questions connexes