SQL Server FOR XML嵌套片段

时间:2017-03-28 13:20:58

标签: sql sql-server xml

我需要生成一个XML片段,如下所示

<Owner>
 <Individual>
  <Name>
   <FirstName>Bob</FirstName>
   <LastName>Smith</LastName>
  </Name>
  <Address>
   <CountryCode>NL</CountryCode>
   <AddressFree>123/456/Netherlands/Netherlands</AddressFree>
  </Address>
 </Individual>
 </Owner>
 <Owner>
 <Individual>
  <Name>
   <FirstName>Tony</FirstName>
   <LastName>Hancock</LastName>
  </Name>
  <Address>
   <CountryCode>US</CountryCode>
   <AddressFree>123/Maryland/United States</AddressFree>
  </Address>
 </Individual>
</Owner>

我正在写这个SQL:

SELECT
    (SELECT  
         b.GivenName [Name/FirstName] ,
         b.FamilyName [Name/LastName] ,
         b.Address_Country [Address/CountryCode] ,
         b.AddressFree [Address/AddressFree]
     FROM    
         dbo.stage_Clients_Merge b
     WHERE   
         b.DWHClientNo = @dwhclientNo
     FOR XML PATH('Individual'), TYPE)
FOR XML PATH('Owner'), TYPE;

但是这段代码不会返回所需的输出,而是将两个人包装在同一个所有者中。

如何更改此功能以实现我的目标?

由于

1 个答案:

答案 0 :(得分:1)

与添加父母NameAddress的方式相同,您可以添加其他父母,&#39;个人&#39;

SELECT  
     b.GivenName [Individual/Name/FirstName] ,
     b.FamilyName [Individual/Name/LastName] ,
     b.Address_Country [Individual/Address/CountryCode] ,
     b.AddressFree [Individual/Address/AddressFree]
FROM dbo.stage_Clients_Merge b
WHERE b.DWHClientNo = @dwhclientNo
FOR XML PATH('Owner'), TYPE