Vasan
Vasan

Reputation: 375

Sql server xml parse

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.

Upvotes: 1

Views: 2150

Answers (1)

marc_s
marc_s

Reputation: 755361

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??

Upvotes: 1

Related Questions