如何在sqlserver中使用OpenXML获取父元素名称

时间:2009-09-14 17:12:48

标签: sql-server xml openxml

如果我有一些xml:

<Users>
    <User>
        <property1>sdfd</property1>
        ...
    <User>
    ... 
</Users>

我的sql是:

SELECT 
    *
FROM
    OpenXML(@idoc, '/Users/User')
    WITH (  
          [property1] varchar(50) 'property1',
          ...
    )

如何获取父元素的名称并将其返回到数据集中?

1 个答案:

答案 0 :(得分:1)

来自MSDN docs on OpenXML的此页面似乎表明您应该能够为父母使用“..”表示法:

declare @idoc int
declare @doc varchar(1000)

set @doc ='<ROOT>
<Customer CustomerID="VINET" ContactName="Paul Henriot">
   <Order OrderID="10248" CustomerID="VINET" EmployeeID="5" 
           OrderDate="1996-07-04T00:00:00">
      <OrderDetail ProductID="11" Quantity="12"/>
      <OrderDetail ProductID="42" Quantity="10"/>
   </Order>
</Customer>
<Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">
   <Order OrderID="10283" CustomerID="LILAS" EmployeeID="3" 
           OrderDate="1996-08-16T00:00:00">
      <OrderDetail ProductID="72" Quantity="3"/>
   </Order>
</Customer>
</ROOT>'

--Create an internal representation of the XML document.
exec sp_xml_preparedocument @idoc OUTPUT, @doc

-- SELECT stmt using OPENXML rowset provider
SELECT *
FROM   OPENXML (@idoc, '/ROOT/Customer/Order/OrderDetail',2)
         WITH (OrderID       int         '../@OrderID',
               CustomerID  varchar(10) '../@CustomerID',
               OrderDate   datetime    '../@OrderDate',
               ProdID      int         '@ProductID',
               Qty         int         '@Quantity')

这也适用于你的情况吗?

<强>更新
试试这个(“伪属性”@mp:parentlocalname):

SELECT *
FROM   OPENXML (@idoc, '/ROOT/Customer/Order/OrderDetail',2)
         WITH (OrderID       int         '../@OrderID',
               CustomerID  varchar(10) '../@CustomerID',
               OrderDate   datetime    '../@OrderDate',
               ProdID      int         '@ProductID',
               Qty         int         '@Quantity',
               ParentNodeName  varchar(50) '@mp:parentlocalname' )

这个现在可以做你想要的吗? :-)

在此article at ExtremeExperts中查看这些“伪属性”的完整列表。

马克