This is my first experience of querying from an XML column in SQL Server and I am close to achieving my desired outcome.
However I would like assistance as there are elements and attributes I would like - I am successful in getting the attributes, however the elements are being merged into a single row instead of splitting them out in different rows.
An example of an XML record in the DB:
<Attributes>
<Map>
<entry key="name" value="John Doe" />
<entry key="department" value="Finance" />
<entry key="employeeNumber" value="123456" />
<entry key="phone">
<value>
<List>
<String>TBA</String>
</List>
</value>
</entry>
<entry key="OrgStructure">
<value>
<List>
<String>top</String>
<String>person</String>
<String>organizationalPerson</String>
<String>user</String>
</List>
</value>
</entry>
<entry key="Membership">
<value>
<List>
<String>Group1</String>
<String>Group2</String>
<String>Group3</String>
</List>
</value>
</entry>
</Map>
</Attributes>
SQL Query:
SELECT
m.c.value('@key', 'varchar(max)') as xmlkey,
m.c.value('@value', 'varchar(max)') as xmlvalue,
m.c.value('.', 'varchar(max)') as xmlString
from #TEMPDB as s
cross apply s.attributes.nodes('Attributes/Map/entry') as m(c)
Result:
xmlkey xmlvalue xmlString
name John Doe
department Finance
employeeNumber 123456
phone NULL TBA
OrgStructure NULL toppersonorganizationalPersonuser
Membership NULL Group1Group2Group3
Desired Result:
xmlkey xmlvalue xmlString
name John Doe
department Finance
employeeNumber 123456
phone NULL TBA
OrgStructure NULL top
OrgStructure NULL person
OrgStructure NULL organizationalPerson
OrgStructure NULL user
Membership NULL Group1
Membership NULL Group2
Membership NULL Group3
I would appreciate any assistance. Thank you!