2017-03-25 173 views
-1

我這裏有XML文件的一小提取物,我將不得不處理:獲取XML節點值和所有嵌套柱節點

<garRoot fileMaster="9371034.0582.30582"> 
    <garTransactions> 
    <garTransaction InnerTransId="89274503"> 
     <garSection> 
     <garSectionCounterFName /> 
     <garColumns /> 
     <garSection> 
      <garSectionName>Header Section</ChapterName> 
      <garSectionCounterFName /> 
      <garColumns /> 
      <garSection> 
      <garSectionName>Startup</ChapterName> 
      <garSectionCounterFName /> 
      <garColumns> 
       <garColumn> 
       <garColText>Idea Date:</garColText> 
       <garColVal>2017-03-22</garColVal> 
       </garColumn> 
       <garColumn> 
       <garColText>Idea Name:</garColText> 
       <garColVal>The Invisible Cloak</garColVal> 
       </garColumn> 
      </garColumns> 
      </garSection> 

我曾嘗試一些代碼嘗試:

  1. 與獲得InnerTransId值爲每個garTransaction開始:

    SELECT T.value('./@InnerTransID','varchar(50)') As InnerTransID FROM @XML.nodes('//garTransaction') AS GarT(T)

  2. 因爲在現實中已經嵌套在其他garSectiongarSection我試圖通過garColumn讓所有garColTextgarColVal:如果我有麻煩

    SELECT C.query('./garColText') As cText , C.query('./garColVal') As cVal FROM @XML.nodes('//garColumn') as garC(C)

是,作爲一個例子我知道每個交易ID都有145列,但我似乎無法將數據鏈接在一起,因爲我需要返回:

InnerTransId cText  cVal 
--------------- ----------- ------------------- 
89274503  Idea Date: 2017-03-22 
89274503  Idea Name: The Invisible Cloak 

回答

1

您可以使用CROSS APPLYOUTER APPLY用於該目的:

SELECT 
    T.value('@InnerTransID','varchar(50)') As InnerTransID 
    , C.value('garColText[1]','varchar(max)') As cText 
    , C.value('garColVal[1]','varchar(max)') As cVal 
FROM @XML.nodes('//garTransaction') AS GarT(T) 
    OUTER APPLY T.nodes('.//garColumn') as garC(C) 

通知nodes('.//garColumn')如何呼籲T,使結果,garC(C),只包含garColumn這與當前garTransaction

+0

謝謝!查詢工作完美;現在我只是想了解它〜我希望在玩SQL語句時我仍然可以問幾個問題? - >昨天我嘗試了一些外部申請,這只是返回10倍以上的行! – Busy