我可以从 SQL Server 存储过程中检索分层数据结构吗?
我有一个 Web 服务,其中一个方法返回一个项目列表,每个项目都拥有另一个项目列表:
<TopLevelItems>
<TopLevelItem field1="a" field2="b" ...>
<LowLevelItem fieldA="1" fieldB="2" .../>
<LowLevelItem fieldA="3" fieldB="4" .../>
</TopLevelItem>
</TopLevelItems>
这些列表是使用简单查询(TopLevelItem
和 LowLevelItem
对应数据库中的相关表)。
到目前为止,要检索所有这些数据,我需要两个查询:一个用于检索顶级项目,该查询执行一次;另一个用于检索顶级项目,该查询仅执行一次。另一个用于检索低级别项目,每个顶级项目执行一次。
然而,这似乎效率极低。我想定义一个存储过程,它执行所有必要的查询并以分层数据结构的形式检索结果。是否可以?如果是这样,怎么办?
I have a Web Service one of whose methods returns a list of items, each of which possesses another list of items:
<TopLevelItems>
<TopLevelItem field1="a" field2="b" ...>
<LowLevelItem fieldA="1" fieldB="2" .../>
<LowLevelItem fieldA="3" fieldB="4" .../>
</TopLevelItem>
</TopLevelItems>
These lists are retrieved from a SQL Server database using simple queries (both TopLevelItem
and LowLevelItem
correspond to related tables in the database).
Until now, to retrieve all this data, I needed two queries: one to retrieve top level items, which was executed once; and another to retrieve low level items, which was executed once per top level item.
However, this seems to be highly inefficient. I would like to define a single stored procedure that performs all the necessary queries and retrieves the result as a hierarchical data structure. Is it possible? If so, how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SQL Server中的层次结构数据可以使用FOR XML来获取。在这种情况下,您只需要编写一个查询来连接表,然后父子关系将表现为嵌套的 XML 元素:
结果:
Hierarchical data in SQL server can be obtained using FOR XML. In this case, you would just need to write a query to join tables, then parent-child relationships will manifest as nested XML elements:
Results:
使用可以直接在 SP 中创建 XML
示例
结果
Use can create the XML in the SP directly
Example
Result