I'm trying to figure out how to pull nested XML elements and turn it into a table result in SQL. A WorkItem always has a group, but Group fields can be nested N times. Is there an easy way to pull JUST the Fields out of an XML field that looks like this:
declare @xml XML = '
<WorkItem>
<Group Name="Base" >
<Field FieldId="361" Name="Assigned To" />
<Field FieldId="362" Name="Stuff" />
<Group Name="Detail">
<Field FieldId="363" Name="Assigned To 2" />
</Group>
</Group>
</WorkItem>'
declare @handle int
declare @status int
exec @status = sp_xml_preparedocument @handle output, @xml
select *
from openxml(@handle, 'WorkItem/Group/Field')
with (
FieldId int,
Name varchar(max)
)
exec sp_xml_removedocument @handle
What I'm getting:
361,Assigned To
362,Stuff
What I'm expecting:
361,Assigned To
362,Stuff
363,Assigned To 2
Thanks!
FROM OPENXML
with the corresponding SPs to prepare and to remove a document is outdated and should not be used any more (rare exceptions exist). Rather use the appropriate methods the XML data type provides. – Shnugo Aug 17 '17 at 9:00