Question

J'ai une table SQL Server 2005 comme celle-ci:

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

avec des données ressemblant à CatégorieIdParentCatégorieIdCatégorieDescription 123nullfoo345123bar

J'aimerais l'interroger dans un document XML comme celui-ci:

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

Est-il possible de faire cela avec FOR XML AUTO, ELEMENTS? Ou dois-je utiliser FOR XML EXPLICIT?

Était-ce utile?

La solution

C’est possible, mais la principale limite est que les niveaux de la hiérarchie doivent être codés en dur. La documentation en ligne de SQL Server décrit comment représenter les hiérarchies au format XML à l'adresse ce lien . Vous trouverez ci-dessous un exemple de requête qui produit le code XML que vous avez 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')
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top