Sql server TSQL:如何在XML中进行自连接以获取嵌套文档?
我有一个SQL Server 2005表,如下所示:Sql server TSQL:如何在XML中进行自连接以获取嵌套文档?,sql-server,tsql,sqlxml,for-xml,Sql Server,Tsql,Sqlxml,For Xml,我有一个SQL Server 2005表,如下所示: create table Taxonomy( CategoryId integer primary key, ParentCategoryId integer references Taxonomy(CategoryId), CategoryDescription varchar(50) ) <taxonomy> <category categoryid="123" categorydescription="foo"&g
create table Taxonomy(
CategoryId integer primary key,
ParentCategoryId integer references Taxonomy(CategoryId),
CategoryDescription varchar(50)
)
<taxonomy>
<category categoryid="123" categorydescription="foo">
<category id="455" categorydescription="bar"/>
</category>
</taxonomy>
数据看起来像
CategoryIdParentCategoryIdCategoryDescription
123345123bar
我想将其查询到如下xml文档中:
create table Taxonomy(
CategoryId integer primary key,
ParentCategoryId integer references Taxonomy(CategoryId),
CategoryDescription varchar(50)
)
<taxonomy>
<category categoryid="123" categorydescription="foo">
<category id="455" categorydescription="bar"/>
</category>
</taxonomy>
是否可以对XML自动元素执行此操作?还是需要使用XML EXPLICIT?这是可能的,但主要限制是层次结构的级别必须是硬编码的。SQLServer联机丛书中描述了如何在以下位置用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')