在MSSQL中混合XML父母和子女

时间:2009-04-16 17:15:14

标签: sql-server xml xpath cookies

我认为我需要的是CROSS APPLY,但我似乎无法弄清楚语法。我在MSSQL 2008数据库中有一组XML,如下所示:

<Cookie>
   <id>Chocolate Chip</id>
   <ChocolateChipPeanutButter>
      ...
   </ChocolateChipPeanutButter>

   <ChocolateChipPecan>
      ...
   </ChocolateChipPecan>
</Cookie>

<Cookie>
   <id>Raisin</id>
</Cookie>

<Cookie>
   <id>Coconut</id>
</Cookie>

<Cookie>
   <id>Sugar</id>
</Cookie>

我正在尝试删除XML,以便我有一个如下所示的结果集:

Cookie Name                   Cookie SubName
___________                   ______________
Chocolate Chip                <null>
Chocolate Chip                ChocolateChipPeanutButter
Chocolate Chip                ChocolateChipPecan
Raisin                        <null>
Coconut                       <null>
Sugar                         <null>

我想我需要写这样的东西(假设XML数据存储在 DECLARE @XMLData XML

SELECT
     TheXML.TheCookie.query('data(./id)')     AS CookieName
   , TheXML.TheCookie.query('.')              AS CookieData
   , Sub.SubCookieName                        AS SubCookieName
FROM
   @XMLData.nodes('//Cookie') AS TheXML(TheCookie)
CROSS APPLY
   (
       SELECT
          TheCookieXML.SubCookieName.query('local-name(.)')
       FROM
          CookieData.nodes('./*') AS TheCookieXML(SubCookieName)
   )

我知道,我知道,这个XML架构对于我正在尝试用它做的很糟糕,但我们假设我们这样使用数据并从那里开始工作。我是在正确的轨道上吗? CROSS APPLY会这样工作吗?蝙蝠侠现在可以救我吗?

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

SELECT
     TheXML.TheCookie.value('(id[1])', 'varchar(20)') AS CookieName
   , TheXML.TheCookie.query('.') AS CookieData
   , Sub.SubCookie.value('local-name(.)', 'varchar(20)') AS SubCookieName
FROM
   @xmlcon.nodes('//Cookie') AS TheXML(TheCookie)
CROSS APPLY
    TheXML.TheCookie.nodes('./*') as Sub(SubCookie)

麻烦 - 这也选择“id”节点: - (

马克