XML返回单独的节点元素

时间:2017-03-01 11:09:45

标签: sql-server xml tsql

我需要以特定格式返回结果

<Applicants xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Applicant>
        <Name>John Smith</Name>
        <Address>1 Smiths Close</Address>
    </Applicant>
    <Applicant>
        <Name>Peter Smith</Name>
        <Address>2 Smiths Close</Address>
    </Applicant>
</Applicants>

但是使用我当前的查询

select A.Name
    , ANL.name
    , A.address AS Address
    , ANL.address AS Address
    from Agents A 
        left join AgentsNonLatin ANL 
            On A.Pn = ANL.Pn AND A.Kd = ANL.kd 
    FOR XML RAW('Applicant'), ROOT('Applicants'), ELEMENTS XSINIL

我将它们组合成一个<Applicant>节点。

<Applicants xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Applicant>
    <Name>John Smith</Name>
    <Name>Peter Smith</Name>
    <Address>1 Smiths Close</Address>
    <Address>2 Smiths Close</Address>
  </Applicant>
</Applicants>

有关需要更改哪些内容以便以所需格式返回它们的想法?

1 个答案:

答案 0 :(得分:2)

在这里使用联盟

SELECT 
      A.Name
    , A.Address 
    FROM Agents A 
UNION
SELECT 
      ANL.Name
    , ANL.Address AS Address
    FROM AgentsNonLatin ANL 
FOR XML RAW('Applicant'), ROOT('Applicants'), ELEMENTS XSINIL