tags:

views:

285

answers:

1

How can I retrieve the fields within an XML field in MS SQL?

Every query I try does not work as intended whenever I use this XML code:

<soap:Envelope xmlns:xsi="[URI]" xmlns:xsd="[URI]" xmlns:soap="[URI]">
  <soap:Body>
    <RunPackage xmlns="[URI]">
      <xmlDoc>
        <Request>
          <SubscriberCode>76547654</SubscriberCode>
          <CompanyCode></CompanyCode>
        </Request>
      </xmlDoc>
    </RunPackage>
  </soap:Body>
</soap:Envelope>

I don't know how to reference the first two tags. I've tried

SELECT TransactionID, T2.Loc.query('data(Request/SubscriberCode)') as 'SubscriberCode'
FROM   TempWorksRequest
CROSS APPLY RequestXML.nodes('soap:Envelope/soap:Body/RunPackage/xmlDoc') as T2(Loc)

With no luck.

+2  A: 

You need to declare the XML namespaces ("soap" in this case, plus another one for the node and anything below) in your XQuery operations:

SELECT 
   TransactionID, 
   T2.Loc.query('declare namespace ns="[URI1]";data(ns:Request/ns:SubscriberCode)') 
     as 'SubscriberCode'
FROM   
   TempWorksRequest
CROSS APPLY 
   RequestXML.nodes('declare namespace soap="[URI]";
                     declare namespace ns="[URI1]";
                     soap:Envelope/soap:Body/ns:RunPackage/ns:xmlDoc') as T2(Loc)

[URI1] needs to be the URI that's defined on the <RunPackage> tag.

Marc

marc_s
Thank you so much! This almost functioned verbatim. I noticed I also was missing a XML declaration tag and was not using the correct namespace URIs!
KTF
Great answer, it helped me as well.
cciotti