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

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

数据看起来像 CategoryIdParentCategoryIdCategoryDescription 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')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top