1

I am using SQL Server 2008. I have a field called RequestParameters in one of my SQL table called Requests with XML data. An example would be:

<RequestParameters xmlns="http://schemas.datacontract.org/2004/07/My.Name.Space" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Id="1">
  <Data z:Id="2" i:type="CheckoutRequest">
    <UserGuid>7ec38c44-5aa6-49e6-9fc7-25e9028f2148</UserGuid>
    <DefaultData i:nil="true" />
  </Data>
</RequestParameters>

I ultimately want to retrieve the value of UserGuid. For that, I am doing this:

SELECT RequestParameters.value('(/RequestParameters/Data/UserGuid)[0]', 'uniqueidentifier') as UserGuid
FROM Requests

However, the results I am seeing are all NULL. What am I doing wrong?

0

2 Answers 2

2

You have to specify the default namespace and use [1] instead of [0].

WITH XMLNAMESPACES(default 'http://schemas.datacontract.org/2004/07/My.Name.Space')
SELECT RequestParameters.value('(/RequestParameters/Data/UserGuid)[1]', 'uniqueidentifier') as UserGuid
FROM Requests;

SQL Fiddle

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

2 Comments

yup , specifying nanespace is necessary . +1
@Noobie [1] is used to specify the first instance of the value you want. You could use [2] to get the second instance if you had more than one UserGuid in your XML. [0] specifies the value before the first and well.. there is nothing before the first so you get nothing back.
-1
  declare @XML xml

  set @XML = "<RequestParameters       xmlns="http://schemas.datacontract.org/2004/07/My.Name.Space"       xmlns:i="http://www.w3.org/2001/XMLSchema-instance"       xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Id="1">
    <Data z:Id="2" i:type="CheckoutRequest">
      <UserGuid>7ec38c44-5aa6-49e6-9fc7-25e9028f2148</UserGuid>
      <DefaultData i:nil="true" />
    </Data>
  </RequestParameters>"

 select @XML.value('(/RequestParameters/Data /UserGuid)[1]', 'varchar')
  '

1 Comment

It could be because this answer does not work. Have you tried it? If not you could test it here

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.