[英]How to return SQL Server 2005/2008 columns as identical child nodes using FOR XML query?
Basically I need to return some data from a SQL Server table in the following XML format: 基本上,我需要以以下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>
I have come up with the following SQL statement: 我想出了以下SQL语句:
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!
谢谢!
You need to unpivot your data. 您需要取消数据透视。
Try using a subquery along the lines of: 尝试按照以下方式使用子查询:
SELECT 'FirstName' as [@name], FirstName as [*]
union all
SELECT 'LastName' as [@name], LastName as [*]
for xml path('field')
Or something along these lines... 或类似的东西...
I don't have SQL with me (on my iPhone today), but I'm thinking about: 我没有SQL(今天在我的iPhone上),但是我在考虑:
select 'Person.Contact' as "@name",
(select (SELECT 'FirstName' as [@name], FirstName as [*]
union all
SELECT 'LastName' as [@name], LastName as [*]
for xml path('field')) from Person.Contact for XML path('row'), TYPE)
for XML path('entity'), root('querydata')
Thank you very much Rob! 非常感谢Rob! You definitely got me on the right track, +1 for you!
您一定使我步入正轨,为您+1! I had to wrap everything in a SELECT * FROM statement, otherwise SQL server complains.
我必须将所有内容包装在SELECT * FROM语句中,否则SQL Server会抱怨。 Here is the final working query:
这是最终的工作查询:
SELECT 'Person.Contact' as "@name",
(SELECT
(SELECT * from (SELECT 'FirstName' as [@name], [FirstName] as [*]
union all
SELECT 'LastName' as [@name], [LastName] as [*]) y
for xml path('field'), TYPE)
from Person.Contact for XML path, TYPE)
for XML path('entity'), root('querydata')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.