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

时间:2020-03-06 15:00:17  来源:igfitidea点击:

我有一个像这样的SQL Server 2005表:

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

数据看起来像
CategoryIdParentCategoryIdCategoryDe​​scription
123nullfoo345123bar

我想将其查询到xml文档中,如下所示:

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

是否可以使用FOR XML AUTO,ELEMENTS来做到这一点?还是我需要使用FOR XML EXPLICIT?

解决方案

可能但主要限制是必须对层次结构的级别进行硬编码。 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')