【问题标题】:MSSQL 2008 get all levels of itemMSSQL 2008 获取所有级别的项目
【发布时间】:2011-06-08 09:58:07
【问题描述】:

假设我在 SQL xml 类型字段中有 xml,例如

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

如何在查询中获取第 n 级项目?

显然要获得您将使用的第一个级别;

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

并且要获得下一个级别,您还需要添加

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

但在运行时我们不知道 xml 可能达到的深度。

谁能指出我正确的方向。

谢谢!

【问题讨论】:

    标签: tsql xquery-sql


    【解决方案1】:

    如果你想要所有项目节点,你可以这样做

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

    结果:

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

    如果你只想要最里面的项目节点,你可以这样做

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

    结果:

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

    【讨论】:

    • 哇真的这么简单,只是一个额外的正斜杠!非常感谢!
    猜你喜欢
    • 2018-12-30
    • 2013-10-03
    • 1970-01-01
    • 2016-02-04
    • 2013-03-25
    • 1970-01-01
    • 2021-04-14
    • 2023-03-26
    • 2015-08-04
    相关资源
    最近更新 更多