1

Please find below the script snippet

declare @xml xml
set @xml = '<Message>

<MessageData>
  <MessageDataSet >
  <id> 1 </id>
  <name>Vasan</name>     
  </MessageDataSet>  
   <MessageDataSet >

    <id> 2 </id>
    <name>Vivek</name>
  </MessageDataSet>  

</MessageData>

</Message>'

SELECT
t.c.value('(id)[1]','varchar(100)')
from
@xml.nodes('/Message/MessageData/MessageDataSet')  AS t(c)

I am getting all the 'id' node values, that is '1' & '2'. My need, I have to directly fetch the value of the second 'id', in this case.it will be '2'. Can anyone let me know the Select query syntax for the same? Thanks.

1 Answer 1

1

How about this:

SELECT
    @xml.value('(/Message/MessageData/MessageDataSet/id)[2]','varchar(100)')

Returns 2 as the value for me. This grabs the exactly second entry inside that XML - if it's not there, you'll get NULL back.

Also: why convert this to a varchar(100) - wouldn't int be a more appropriate type here??

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

1 Comment

@mark_s, sorry missed to answer your other query, the varchar(100) was just a stop gap stuff, you are right, I will be using the appropriate type.

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.