2012-10-04 76 views
2

我正在使用SQL Server 2008,並試圖使用EXPLICIT模式與FOR XML生成自定義xml。使用FOR XML的SQL Server EXPLICIT模式

我也有一對多的關係,下面的查詢

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 

enter image description here

我想人的父母和地址孩子可能是多個,因爲人們解決有一對多的關係。

我寫了下面的查詢

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> 

有人能幫我一把!

回答

8

我建議溝渠​​並使用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

+0

感謝您的幫助,顯式模式很爛。 –

1

要正確使用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