0

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

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!
Great answer, it helped me as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.