1

In sql server xml column I have xml like this:

<Test>  
    <Operations>
        <Operations type="OperationSend">
            <OperationSend>                             
                <ToCompanyId>1</ToCompanyId>
                <Date>2011-05-01T00:00:00</Date>                
            </OperationSend>
        </Operations>
        <Operations type="OperationSell">
            <OperationSell>
                <ToCompanyId>33</ToCompanyId>
                <Amount>12</Amount>
            </OperationSell>
        </Operations>
        <Operations type="OperationEdit">
            <OperationEdit>
                <ToCompanyId>12</ToCompanyId>
                <Date>2011-11-01T00:00:00</Date>    
            </OperationEdit>
        </Operations>
    </Operations>
</Test>

I need to take ToCompanyId from last operation (12). I came to something like this. What should be in ??? when there can be any operation type with ToCompanyId.

select testxml.query('(/Test/Operations/Operations)[last()]/???/ToCompanyId') from dbo.MyXmlTable
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
bizon
  • 2,406
  • 2
  • 25
  • 28

3 Answers3

3

You can use *

select testxml.query('(/Test/Operations/Operations)[last()]/*/ToCompanyId').value('.', 'int')
from MyXmlTable
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
1

Assuming that you have set your xml to be a variable named @x then this is how to get your 12.

select  x.header.value('.', 'int') 
                from @x.nodes('//Test/Operations/Operations[last()]/OperationSend/ToCompanyId')
                 as x(header) 

the query would be slightly different to get from a column of a table but the XPATH would be the same.

select testxml.query('//Test/Operations/Operations[last()]/OperationSend/ToCompanyId') from dbo.MyXmlTable
Avitus
  • 15,640
  • 6
  • 43
  • 53
1

Put node() instead of ???

node() matches all nodes of any kind

krolik
  • 5,712
  • 1
  • 26
  • 30