我有一个像这样的SQL Server 2005表:
create table Taxonomy(
CategoryId integer primary key,
ParentCategoryId integer references Taxonomy(CategoryId),
CategoryDescription varchar(50)
)
数据看起来像
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>
是否可以使用FOR XML AUTO,ELEMENTS执行此操作?或者我需要使用FOR XML EXPLICIT吗?
答案 0 :(得分: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')