Sql server 在MSSQL中混合XML父级和子级

Sql server 在MSSQL中混合XML父级和子级,sql-server,xml,xpath,cookies,Sql Server,Xml,Xpath,Cookies,我想我需要的是交叉应用,但我似乎无法理解语法。我在MSSQL 2008数据库中有一组XML,如下所示: <Cookie> <id>Chocolate Chip</id> <ChocolateChipPeanutButter> ... </ChocolateChipPeanutButter> <ChocolateChipPecan> ... </ChocolateC

我想我需要的是交叉应用,但我似乎无法理解语法。我在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>
Cookie Name                   Cookie SubName
___________                   ______________
Chocolate Chip                <null>
Chocolate Chip                ChocolateChipPeanutButter
Chocolate Chip                ChocolateChipPecan
Raisin                        <null>
Coconut                       <null>
Sugar                         <null>
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)

我知道,我知道,这个XML模式对于我试图用它来做的事情来说很糟糕,但让我们假设我们以这种方式处理数据,并从那里开始工作。我走对了吗?CROSS APPLY会像这样工作吗?现在连蝙蝠侠都能救我吗?

试试这样的方法:

<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>
Cookie Name                   Cookie SubName
___________                   ______________
Chocolate Chip                <null>
Chocolate Chip                ChocolateChipPeanutButter
Chocolate Chip                ChocolateChipPecan
Raisin                        <null>
Coconut                       <null>
Sugar                         <null>
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”节点:-(


Marc

xml.TheCookie.nodes('./*[local-name()!='id'])作为Sub(SubCookie)注释的第三次尝试…上面包含一些单引号故障,并不严重。另一种更简单的XPath:TheXML.TheCookie.nodes('./*[not(self::id)])非常好的评论,Tomalak!谢谢-排除节点的技术很好!Tomalak,XPATH非常有用,我希望你能从评论的投票中获得代表。@marc_s:哦,我差点忘了。+1作为答案。微软Cookie Master 2010的原型可能是?:-)