gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:46:54 24 4
gpt4 key购买 nike

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

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

数据看起来像
CategoryIdParentCategoryIdCategoryDescription
123nullfoo345123bar
<br/>



<p>I'd like to query it into an xml document like this:</p>

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

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

最佳答案

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

关于sql-server - TSQL:如何在 XML 中进行自连接以获得嵌套文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/160374/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com