如何在SQLXML中获取每个属性的名称,值和父元素名称?

时间:2010-07-07 10:43:44

标签: sql xml sqlxml

鉴于此SQL:

DECLARE @content XML
SET @content =
'<people>
  <person id="1" bimble="1">
    <firstname bobble="gomble">John</firstname>
    <surname>Doe</surname>
  </person>
  <person id="2" bimble="11">
    <firstname bobble="zoom">Mary</firstname>
    <surname>Jane</surname>
  </person>
  <person id="4" bimble="10">
    <firstname bobble="womble">Matt</firstname>
    <surname>Spanner</surname>
  </person>
</people>'

我想检索每个属性,它的值和父元素的名称作为表:

Parent Name Attribute Name Attribute Value
----------- -------------- ---------------
person      id             1
person      bimble         1
firstname   bobble         gomble
person      id             2
person      bimble         11
firstname   bobble         zoom
person      id             4
person      bimble         10
firstname   bobble         womble

1 个答案:

答案 0 :(得分:4)

我最初的回答(对我自己的问题):

SELECT
    elem.value('local-name(..)', 'nvarchar(10)') AS 'Parent Name',
    elem.value('local-name(.)', 'nvarchar(10)') AS 'Attribute Name',
    elem.value('.', 'nvarchar(10)') AS 'Attribute Value'
FROM
    @content.nodes('//@*') AS El(elem)