I'm reading a XML document using XQuery in SQL Server. This is my XML:
declare @xml as xml='
<contactdata>
<contacts>
<groupkey>24</groupkey>
<groupname>Test Group One</groupname>
<contact>
<contactkey>100</contactkey>
<contactname>Test Contact One</contactname>
</contact>
<contact>
<contactkey>111</contactkey>
<contactname>Test Contact Two</contactname>
</contact>
</contacts>
<contacts>
<groupkey>26</groupkey>
<groupname>Test Group Two</groupname>
<contact>
<contactkey>101</contactkey>
<contactname>Test Contact Six</contactname>
</contact>
</contacts>
</contactdata>';
In order to retrieve the each contact details under every group, I'm using this XQuery syntax
select
c.value('(groupkey)[1]','int'),
c.value('(groupname)[1]','nvarchar(max)'),
c.value('(contact/contactkey)[1]','int'),
c.value('(contact/contactname)[1]','nvarchar(max)')
from
@xml.nodes('contactdata/contacts') as Contacts(c)
But this will return only the first contact under each group.
But I need this output
Please help.