开发者

MSSQL 2008 get all levels of item

say I have xml in a SQL xml type field e.g.

    @x='<root>
         <item>
           <title></title>
           <item>
             <title></title>
           </item>
         </item>
       </root>'

How would I go about getting nth level items in a query?

Obviously to get the first level you would use;

    select
     t.p.query('.')
    from
     @x.nodes('/root/item') t(p)

and to get the next level as well you would add

    cross apply
         @x.nodes('/root/item/item')

but at runtime we do not know the depth the xml 开发者_开发百科may go to.

Can anyone point me in the right direction.

Thanks!


If you want all item nodes you can do like this

select t.p.query('.')
from @x.nodes('//item') t(p)

Result:

(No column name)
<item><title /><item><title /></item></item>
<item><title /></item>

If you want only the innermost item node you can do like this

select
  t.p.query('.')
from @x.nodes('//item[count(item) = 0]') t(p)

Result:

(No column name)
<item><title /></item>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜