3

我有一个这样的 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?

4

1 回答 1

3

这是可能的,但主要限制是层次结构的级别必须是硬编码的。SQL Server 联机丛书在此链接中描述了如何用 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')
于 2008-10-02T03:38:30.840 回答