TSQL:如何在XML中进行自联接以获取嵌套文档?

时间:2008-10-02 00:29:28

标签: sql-server tsql sqlxml for-xml

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

1 个答案:

答案 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')