views:

33

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: I want to select the AccNumber value.

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <soap:Header>
    <AuthSoapHd xmlns="https://temp.uri.com/Mngmt/"&gt;
      <System>System1</System>
    </AuthSoapHd>
  </soap:Header>
  <soap:Body>
    <PrintList xmlns="https://temp.uri.com/Mngmt/"&gt;
      <Account>
        <AccNumber xmlns="https://temp.uri.com/Project/Object/Data"&gt;990368644&lt;/AccNumber&gt;
      </Account>
    </PrintList>
  </soap:Body>
</soap:Envelope>

I tried multiple varations of the following with no sucess

Select [RequestXML].query('/Envelope/Body/PrintList/Account/AccNumber')
  FROM [dbo].[Table1]
+2  A: 

You're ignoring the XML namespace that is in play - you need to pay attention to that!

WITH XMLNAMESPACES('http://schemas.xmlsoap.org/soap/envelope/' AS soap,
                   'https://temp.uri.com/Project/Object/Data' AS data,
                   'https://temp.uri.com/Mngmt/' AS mgmt)

SELECT 
   RequestXML.value('(/soap:Envelope/soap:Body/mgmt:PrintList/mgmt:Account/data:AccNumber)[1]',
                    'BIGINT') AS 'AccNumber'
FROM 
   [dbo].[Table1]

That hopefully works!

marc_s
Thank you Marc_S! This was perfect! No modifications needed was spot on.
Nic