从SQL中的XML中提取元素

时间:2017-08-16 15:36:27

标签: sql sql-server xml

我试图弄清楚如何提取嵌套的XML元素并将其转换为SQL中的表结果。 WorkItem总是有一个组,但组字段可以嵌套N次。有没有一种简单的方法可以将字段拉出XML字段,如下所示:

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

我得到了什么:

361,Assigned To
362,Stuff

我期待的是:

361,Assigned To
362,Stuff
363,Assigned To 2

谢谢!

1 个答案:

答案 0 :(得分:5)

我认为使用XQuery更好:

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>';


SELECT 
    n.value('@FieldId', 'int') FieldId, 
    n.value('@Name', 'varchar(250)') Name
FROM 
    @xml.nodes('/WorkItem//Field') xml(n);

输出:

FieldId     Name
----------- --------------------
361         Assigned To
362         Stuff
363         Assigned To 2