2015-11-23 37 views
2

我想從SQL Server生成XML選擇查詢。我想輸出看起來像這樣:從SQL選擇查詢輸出複雜的XML

<Root Version="3.3" UnitsOfMeasure="metric"> 
<Header> 
    <HeaderID CountryCode="TH" LanguageCode="tha" Name="บริษัท เลิศวนิชออยล์ จำกัด สาขา 1" IDType="Local">88</HeaderID> 
</Header> 
<Item> 
    <ItemID Name="Premium Unleaded">4021</ItemID> 
    <SubItem> 
     <SubItemID Name="T3">3</SubItemID> 
     <TimeStamp> 
      <Date>2015-09-19</Date> 
      <Time>14:09</Time> 
     </TimeStamp> 
    </SubItem> 
</Item> 
<Item> 
    <ItemID Name="Diesel">4041</ItemID> 
    <SubItem> 
     <SubItemID Name="T1">1</SubItemID> 
     <TimeStamp> 
      <Date>2015-09-19</Date> 
      <Time>14:09</Time> 
     </TimeStamp> 
    </SubItem> 
    <SubItem> 
     <SubItemID Name="T7">7</SubItemID> 
     <TimeStamp> 
      <Date>2015-09-19</Date> 
      <Time>14:09</Time> 
     </TimeStamp> 
    </SubItem> 
</Item> 
</Root> 

數據庫結構是

  • HeaderTable通過加入到ItemTableHeaderID外鍵
  • ItemTable加入到通過HeaderIDSubItemTableItemID作爲主鍵

讓我知道如果您需要更多信息,請通知我們。

+0

我已經做了這相當成功地使用FOR XML命令。文檔也很好。 –

+0

我在哪裏可以找到文檔? –

+0

微軟的文檔是一個堅實的開始在這一個地方,嘗試在這裏; https://msdn.microsoft.com/en-GB/library/ms178107.aspx –

回答

0

從SQL查詢請參閱下面的示例XML代...

SELECT e.EmployeeID AS "@EmpID", 
    c.FirstName AS "EmployeeName/FirstName", 
    c.MiddleName AS "EmployeeName/MiddleName", 
    c.EmailAddress, 
    c.LastName AS "EmployeeName/LastName" 
FROM HumanResources.Employee AS e 
    INNER JOIN Person.Contact AS c 
    ON c.ContactID = e.ContactID 
WHERE c.FirstName = 'Rob' 
FOR XML PATH ('Employee'), ROOT ('Employees'), ELEMENTS XSINIL; 

生成的XML如下:...同樣相應地改變你的代碼..: -

<Employees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <Employee EmpID="4"> 
    <EmployeeName> 
     <FirstName>Rob</FirstName> 
     <MiddleName xsi:nil="true" /> 
    </EmployeeName> 
    <EmailAddress>[email protected]</EmailAddress> 
    <EmployeeName> 
     <LastName>Walters</LastName> 
    </EmployeeName> 
    </Employee> 
    <Employee EmpID="168"> 
    <EmployeeName> 
     <FirstName>Rob</FirstName> 
     <MiddleName>T</MiddleName> 
    </EmployeeName> 
    <EmailAddress>[email protected]</EmailAddress> 
    <EmployeeName> 
     <LastName>Caron</LastName> 
    </EmployeeName> 
    </Employee> 
</Employees> 
+0

@TobyJackson請參閱上面的代碼,讓我知道它是否工作或不!我希望最新的更新文章能夠滿足您的要求。 –