2017-05-09 103 views
0

我XML在數據看起來像這樣選擇XML節點在SQL服務器

DECLARE @XML XML 
DECLARE @output XML 
SET @XML='<ROOT> 
    <HDR> 
     <NBR>21</NBR> 
     <DT>2009-08-17</DT> 
    </HDR> 
    <OTHERINFO> 
     <RAT> 
      <ASMT_DT>2015-08-10</ASMT_DT> 
     </RAT> 
     <RAT> 
      <ASMT_DT>2014-08-10</ASMT_DT> 
      <INDICATOR>1</INDICATOR> 
     </RAT> 
     <RAT> 
      <ASMT_DT>2013-08-10</ASMT_DT> 
      <INDICATOR>1</INDICATOR> 
     </RAT> 
    </OTHERINFO> 
</ROOT>' 

我要打印XML與節點沒有<INDICATOR>1</INDICATOR>即這樣

SET @output= 
'<ROOT> 
    <HDR> 
     <NBR>21</NBR> 
     <DT>2009-08-17</DT> 
    </HDR> 
    <OTHERINFO> 
     <RAT> 
      <ASMT_DT>2015-08-10</ASMT_DT> 
     </RAT> 
    </OTHERINFO> 
</ROOT>' 
SQL Server表

我該怎麼做? 感謝

回答

2

您可以使用.modify()擺脫所有節點的你不希望保留:

SET @XML='<ROOT> 
    <HDR> 
     <NBR>21</NBR> 
     <DT>2009-08-17</DT> 
    </HDR> 
    <OTHERINFO> 
     <RAT> 
      <ASMT_DT>2015-08-10</ASMT_DT> 
     </RAT> 
     <RAT> 
      <ASMT_DT>2014-08-10</ASMT_DT> 
      <INDICATOR>1</INDICATOR> 
     </RAT> 
     <RAT> 
      <ASMT_DT>2013-08-10</ASMT_DT> 
      <INDICATOR>1</INDICATOR> 
     </RAT> 
    </OTHERINFO> 
</ROOT>'; 

SET @XML.modify('delete /ROOT/OTHERINFO/RAT[INDICATOR=1]'); 
SELECT @XML; 

另 - inlineable! - 方法是FLWOR XQuery

SELECT @XML.query 
(' let $hdr:=/ROOT/HDR 
    let $oi:=/ROOT/OTHERINFO 
    return 
    <ROOT> 
    {$hdr} 
    <OTHERINFO> 
    { 
     for $r in $oi/RAT[empty(INDICATOR) or INDICATOR/text()!="1"] 
     return $r 
    } 
    </OTHERINFO> 
    </ROOT> 
'); 
+0

你有......我等待你的答案 –