使用FOR XML的SQL Server EXPLICIT模式

时间:2012-10-04 20:44:16

标签: sql-server-2008 tsql for-xml for-xml-explicit

我正在使用SQL Server 2008,而我正尝试使用EXPLICIT模式生成自定义xml。

我有以下查询的一对多关系

FOR XML

enter image description here

我希望作为父母的人和孩子的地址可能是多个,因为人们要解决一对多关系。

我写了以下查询

select  
    p.personid, p.firstname, a.P_City 
from 
    tblPeople p with (nolock) 
left outer join 
    tblAddresses a with (nolock) on p.personid = a.personid 
where 
    p.personid = 120773

输出如下,它被破坏了xml与人嵌套我的代码确实存在一些问题。

 select 1 as TAG,
        null as parent, 
        p.personid as [person!1!personid],
        p.FirstName as [person!1!firstname],

        null as [addr!2!] 
        from tblPeople p with (nolock) where p.PersonID in (120773,117396)

        union all 

select 2,1, 
        p.PersonID, p.FirstName, a.P_City from tblAddresses a with(nolock), tblPeople p 
        where p.PersonID=a.PersonID and p.PersonID in (120773,117396)

        for xml explicit

有人可以帮帮我!!!

2 个答案:

答案 0 :(得分:9)

我建议放弃FOR XML EXPLICIT并改用FOR XML PATH/ROOT

在此处使用此查询:

select  
    p.personid AS "@ID", 
    p.firstname, p.LastName,
    (
        SELECT AddressID AS "@ID", City
        FROM dbo.Address a 
        WHERE a.PersonID = p.PersonID
        FOR XML PATH('addr'), TYPE
    ) AS Addresses
from 
    Person p with (nolock) 
where 
    p.personid = 120773
FOR XML PATH('Person'), ROOT('People')

您将获得此输出XML:

<People>
  <Person ID="120773">
    <firstname>John</firstname>
    <LastName>Doyle</LastName>
    <Addresses>
      <addr ID="1">
        <City>Annapolis</City>
      </addr>
      <addr ID="2">
        <City>Mount Rainier</City>
      </addr>
    </Addresses>
  </Person>
</People>

根据需要调整它。详细了解FOR XML PATH on MSDN

答案 1 :(得分:2)

为了正确使用FOR XML EXPLICIT,ORDER BY是基础。 检查一下

select 1 as TAG,
        null as parent, 
        p.personid as [person!1!personid],
        p.FirstName as [person!1!firstname],

        null as [addr!2!] 
        from tblPeople p with (nolock) where p.PersonID in (120773,117396)

        union all 

select 2,1, 
        p.PersonID, p.FirstName, a.P_City from tblAddresses a with(nolock), tblPeople p 
        where p.PersonID=a.PersonID and p.PersonID in (120773,117396)
ORDER BY [person!1!personid], [addr!2!] 
        for xml explicit