4

我正在使用 SQL Server 2008,并且正在尝试使用EXPLICIT带有FOR XML.

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

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

在此处输入图像描述

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

我写了以下查询

 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

输出如下,这是嵌套的人破坏的xml,我的代码肯定有问题。

<person personid="117396" firstname="David"/>
    <person personid="120773" firstname="Doyle">
        <addr>Mount Rainier</addr>
        <addr>Annapolis</addr>
</person>

有没有人可以帮帮我!!!

4

2 回答 2

11

我建议放弃FOR XML EXPLICITFOR 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 PATHMSDN的更多详细信息。

于 2012-10-04T20:53:34.003 回答
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
于 2012-10-10T16:46:14.267 回答