3

I have a SQL Server 2005 table like this:

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

with data looking like CategoryIdParentCategoryIdCategoryDescription 123nullfoo345123bar

I'd like to query it into an xml document like this:

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

Is it possible to do this with FOR XML AUTO, ELEMENTS? Or do I need to use FOR XML EXPLICIT?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Danimal
  • 7,672
  • 8
  • 47
  • 57

1 Answers1

3

It is possible but the main limitation is that the levels of the hierarchy must be hard coded. The SQL Server Books Online has a description of how to represent hierarchies in XML at this link. Below is a sample query that produces the XML you requested:

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')
Sixto Saez
  • 12,610
  • 5
  • 43
  • 51