Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server TSQL:如何在XML中进行自连接以获取嵌套文档?_Sql Server_Tsql_Sqlxml_For Xml - Fatal编程技术网

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

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

我有一个SQL Server 2005表,如下所示:

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