如何使用FOR XML查询将SQL Server 2005/2008列作为相同的子节点返回?

时间:2010-01-23 01:54:42

标签: sql sql-server sql-server-2005 for-xml

基本上我需要以下列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>

但我没有进一步。谢谢!

2 个答案:

答案 0 :(得分:1)

您需要取消存储数据。

尝试使用以下行的子查询:

SELECT 'FirstName' as [@name], FirstName as [*]
union all
SELECT 'LastName' as [@name], LastName as [*]
for xml path('field')

或者沿着这些方向......

我没有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')

答案 1 :(得分:0)

非常感谢Rob!你绝对让我走上了正确的道路,为你+1!我必须在SELECT * FROM语句中包装所有内容,否则SQL服务器会抱怨。这是最终的工作查询:

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