简体   繁体   中英

Parse XML data in SQL Server table

I was studing a little about xml parsing, using examples I found here in stackoverflow but I came across a doubt. If I have something like this

DECLARE @xml xml
SET @xml = 
'<?xml version="1.0" encoding="UTF-8"?> 
<oo_outbound_order>   
         <oo_master>
              <Code>123</Code>
              <Name>Branan</Name> 
         </oo_master> 
    </oo_outbound_order>'

SELECT 
    n.value('(./Code/text())[1]','int') as CODE
 , n.value('(./Name/text())[1]','Varchar(50)') as NAME
FROM @xml.nodes('/oo_outbound_order/oo_master') as a(n)

I get something like this

CODE    NAME
123     Branan

but if one of the fields I want to store it as xml

<?xml version="1.0" encoding="UTF-8"?> 
<oo_outbound_order> 
        <Active>true</Active>
        <Weight>0.02</Weight>
         <oo_master>
              <Code>123</Code>
              <Name>Branan</Name> 
        </oo_master>
    </oo_outbound_order> 

And I want to get something like this

 Active   Weight    ColWithXML
  true     0.02     <oo_master><Code>123</Code><Name>Branan</Name></oo_master>


SELECT 
    n.value('Active[1][not(@xsi:nil = "true")]', 'BIT') as Active
 , n.value('Weight[1][not(@xsi:nil = "true")]', 'DECIMAL(29,5)') as Weight
, ??????????????????

How can I do that? Thank you

query() method

fiddle

DECLARE @xml xml;

select @xml ='<?xml version="1.0" encoding="UTF-8"?> 
<oo_outbound_order> 
    <Active>true</Active>
    <Weight>0.02</Weight>
     <oo_master>
          <Code>123</Code>
          <Name>Branan</Name> 
    </oo_master>
</oo_outbound_order>';

SELECT 
   n.value('Active[1][not(@xsi:nil = "true")]', 'BIT') as Active
 , n.value('Weight[1][not(@xsi:nil = "true")]', 'DECIMAL(29,5)') as Weight
 , a.n.query('./oo_master') as explicitcurrentnode_master
 , a.n.query('oo_master') as impliedcurrentnode_master
 , a.n.query('./Active') as Activexml
 , a.n.query('./oo_master/Name') as master_Namexml
FROM @xml.nodes('/oo_outbound_order') as a(n);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM