在SQL Server中使用For XML格式化XML

时间:2011-09-15 14:26:24

标签: sql-server xml

我现在改为使用 XML PATH ,这会产生更好的结果,但仍然不完美。

SELECT TOP 5
    CT.ID AS [ID]
    ,CT.TITLE AS [Title]
    ,CT.TELEPHONE AS [Tel]
    ,AD.LINE1 AS [Addresses/Address/Line1]
FROM CONTACT CT
INNER JOIN METADATA MD ON CT.CONTACTID = MD.OWNERID
INNER JOIN ADDRESS AD ON MD.TOOWNERID = AD.ADDRESSID
WHERE CT.ID IS NOT NULL
FOR XML PATH ('ContactDetails'), root ('LeanerData');

此处显示的多个联系人节点的结果 ID 539091 重复两次:

<Records>
  <Contact>
    <ID>535317</ID>
    <Tel>7859243561</Tel>
    <Home>1</Home>
    <Addresses>
      <Address>
        <Line1>Address 1</Line1>
      </Address>
    </Addresses>
  </Contact>
  <Contact>
    <ID>539091</ID>
    <Tel>9876543231</Tel>
    <Home>0</MobileTel>
    <Addresses>
      <Address>
        <Line1>Address 3</Line1>
      </Address>
    </Addresses>
  </Contact>
  <Contact>
    <ID>539091</ID>
    <Tel>9876543231</Tel>
    <Home>0</MobileTel>
    <Addresses>
      <Address>
        <Line1>Address 4</Line1>
      </Address>
    </Addresses>
  </Contact>
</Records>

我正试图获得这种特殊格式。

<Records>
  <Contact>
    <ID>535317</ID>
    <Tel>7859243561</Tel>
    <Home>1</Home>
    <Addresses>
      <Address>
        <Line1>Address 1</Line1>
      </Address>
    </Addresses>
  </Contact>
  <Contact>
    <ID>539091</ID>
    <Tel>9876543231</Tel>
    <Home>0</MobileTel>
    <Addresses>
      <Address>
        <Line1>Address 3</Line1>
      </Address>
      <Address>
        <Line1>Address 4</Line1>
      </Address>
    </Addresses>
  </Contact>
</Records>

1 个答案:

答案 0 :(得分:2)

在转换为xml之前,您需要按顺序获取行。试试这个。

SELECT TOP 5
    1 AS TAG
    ,0 AS PARENT
    ,CT.ID [Contact!1!ID!ELEMENT]
    ,CT.TELEPHONE [Contact!1!Tel!ELEMENT]
    ,CT.TEL [Contact!1!Home!ELEMENT]
    ,NULL [Addresses!2]
    ,NULL [Address!3!Line1!ELEMENT]
FROM CONTACT CT
UNION
SELECT
    2 AS TAG
    ,1 AS PARENT
    ,CT.ID [Contact!1!ID!ELEMENT]
    ,NULL [Contact!1!Tel!ELEMENT]
    ,NULL [Contact!1!Home!ELEMENT]
    ,NULL [Addresses!2]
    ,NULL [Address!3!Line1!ELEMENT]
FROM CONTACT CT
INNER JOIN METADATA MD ON CT.CONTACTID =MD.OWNERID
INNER JOIN ADDRESS AD ON MD.TOOWNERID = AD.ADDRESSID
UNION
SELECT
    3 AS TAG
    ,2 AS PARENT
    ,CT.ID [Contact!1!ID!ELEMENT]
    ,NULL [Contact!1!Tel!ELEMENT]
    ,NULL [Contact!1!Home!ELEMENT]
    ,NULL [Addresses!2]
    ,AD.LINE1 [Address!3!Line1!ELEMENT]
FROM CONTACT CT
INNER JOIN METADATA MD ON CT.CONTACTID = MD.OWNERID
INNER JOIN ADDRESS AD ON MD.TOOWNERID = AD.ADDRESSID
ORDER BY [Contact!1!ID!ELEMENT]
FOR XML EXPLICIT, ROOT('Records')

使用for xml路径的版本:

select C.ID,
       C.TELEPHONE as Tel,
       C.TEL as Home,
       (select A.Line1
        from Metadata as M
          inner join Address as A
            on M.ToOwnerID = A.AddressID
        where M.OwnerID = C.ContactID 
        for xml path('Address'), root('Addresses'), type)
from Contact as C
for xml path('Contact'), root('Records')