如何使用 FOR XML 查询将 SQL Server 2005/2008 列作为相同的子节点返回?
基本上,我需要以以下 XML 格式从 SQL Server 表返回一些数据:
<querydata>
<entity name="Person.Contact">
<row>
<field name="FirstName">Gustavo</field>
<field name="LastName">Achong</field>
</row>
<row>
<field name="FirstName">Catherine</field>
<field name="LastName">Abel</field>
</row>
...
</entity>
</querydata>
我已经提出了以下 SQL 语句:
select 'Person.Contact' as "@name",
(select FirstName, LastName from Person.Contact for XML path('row'), TYPE)
for XML path('entity'), root('querydata')
产生以下输出:
<querydata>
<entity name="Person.Contact">
<row>
<FirstName>Gustavo</FirstName>
<LastName>Achong</LastName>
</row>
<row>
<FirstName>Catherine</FirstName>
<LastName>Abel</LastName>
</row>
....
</entity>
</querydata>
但我没有进一步了解。谢谢!
Basically I need to return some data from a SQL Server table in the following XML format:
<querydata>
<entity name="Person.Contact">
<row>
<field name="FirstName">Gustavo</field>
<field name="LastName">Achong</field>
</row>
<row>
<field name="FirstName">Catherine</field>
<field name="LastName">Abel</field>
</row>
...
</entity>
</querydata>
I have come up with the following SQL statement:
select 'Person.Contact' as "@name",
(select FirstName, LastName from Person.Contact for XML path('row'), TYPE)
for XML path('entity'), root('querydata')
Which produces this output:
<querydata>
<entity name="Person.Contact">
<row>
<FirstName>Gustavo</FirstName>
<LastName>Achong</LastName>
</row>
<row>
<FirstName>Catherine</FirstName>
<LastName>Abel</LastName>
</row>
....
</entity>
</querydata>
But I have gotten no further. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要取消数据透视。
尝试使用以下子查询:
或者类似的东西...
我没有SQL(今天在我的iPhone上),但我在考虑:
You need to unpivot your data.
Try using a subquery along the lines of:
Or something along these lines...
I don't have SQL with me (on my iPhone today), but I'm thinking about:
非常感谢罗布!你绝对让我走上了正确的道路,为你+1!我必须将所有内容包装在 SELECT * FROM 语句中,否则 SQL 服务器会抱怨。这是最终的工作查询:
Thank you very much Rob! You definitely got me on the right track, +1 for you! I had to wrap everything in a SELECT * FROM statement, otherwise SQL server complains. Here is the final working query: