2013-12-09 55 views
0

1.我有如下的XML數據,Child3可能有也可能沒有Child4.If Child4在那裏,應該添加另一列。具有不同級別子節點的OpenXml SQL

<Parent name="ABC"> 
     <Child name="123"> 
      <Child1 text="child123" /> 
      <Child1 text="Child345" />  
      <Child1 text="Status"> 
       <Child2 text="Pending"> 
       <Child3 text="Excise" /> 
       <Child3 text="Financial" />   
       </Child2 > 
       <Child2 text="Over"> 
       <Child3 text="A1111" /> 
       </Child2 > 
      </Child1 > 
      </Child > 
     </Parent `> 

我要像一個結果:

 ABC 123 child123 null  null`` 
     ABC 123 Child345 null  null  
     ABC 123 Status  Pending Excise 
     ABC 123 Status  Pending Financial 
     ABC 123 Status  Over  A1111 

我寫這樣的查詢:

 SELECT Parent ,Child, Child1, Child2, Child3 
     FROM OPENXML(@hDoc, '/Parent /Child /Child1 /Child2 /Child3 ',2) 
     WITH 
     (
     ReleaseInfo [varchar](max) '../../../../@name', 
     L1Data [varchar](max) '../../../@name', 
     L2Data [varchar](max) '../../@text',` 
     L3Data [varchar](max) '../@text', 
     L4Data [varchar](max) '@text') 

我沒有得到第2條記錄。請建議。

回答

1
declare @XML xml = ' 
<Parent name="ABC"> 
    <Child name="123"> 
    <Child1 text="child123" /> 
    <Child1 text="Child345" /> 
    <Child1 text="Status"> 
     <Child2 text="Pending"> 
     <Child3 text="Excise" /> 
     <Child3 text="Financial" /> 
     </Child2> 
     <Child2 text="Over"> 
     <Child3 text="A1111" /> 
     </Child2> 
    </Child1> 
    </Child> 
</Parent>' 

select P.X.value('@name', 'varchar(max)') as Parent, 
     C.X.value('@name', 'varchar(max)') as Child, 
     C1.X.value('@text', 'varchar(max)') as Child1, 
     C2.X.value('@text', 'varchar(max)') as Child2, 
     C3.X.value('@text', 'varchar(max)') as Child3 
from @xml.nodes('/Parent') as P(X) 
    outer apply P.X.nodes('Child') as C(X) 
    outer apply C.X.nodes('Child1') as C1(X) 
    outer apply C1.X.nodes('Child2') as C2(X) 
    outer apply C2.X.nodes('Child3') as C3(X) 
+0

非常感謝! – user3083626

相關問題