代码之家  ›  专栏  ›  技术社区  ›  hallie

SQL Server 2005 XML查询

  •  2
  • hallie  · 技术社区  · 14 年前

    我对查询sql server 2005中的xml数据类型还不熟悉。有谁能帮我创建一个查询来满足我的需求吗?这是我专栏的一个场景。

    Column Name: Cabinet
    
    /*Row 1 XML Data*/
    <shelf>
     <box>
       <item type="pencil" color="blue"/>
       <item type="pencil" color="red"/>
       <item type="paper" color="white"/>
       <item type="ribbon" color="red"/>
     </box>
    <shelf>
    
    /*Row 2 XML Data*/
    <shelf>   
      <item type="pencil" color="yellow"/>
      <item type="can" color="blue"/>
      <item type="scissor" color="yellow"/>
    <shelf>
    
    Desired Output:
    4
    3
    

    我想计算“item”节点的数量,而不考虑其类型和颜色。提前谢谢。

    1 回复  |  直到 14 年前
        1
  •  2
  •   Adriaan Stander    14 年前

    看看这个( 完整工作示例 )

    DECLARE @Table TABLE(
            Cabinet XML
    )
    
    INSERT INTO @Table SELECT
    '<shelf> 
     <box> 
       <item type="pencil" color="blue"/> 
       <item type="pencil" color="red"/> 
       <item type="paper" color="white"/> 
       <item type="ribbon" color="red"/> 
     </box> 
    </shelf>'
    
    INSERT INTO @Table SELECT
    '<shelf>    
      <item type="pencil" color="yellow"/> 
      <item type="can" color="blue"/> 
      <item type="scissor" color="yellow"/> 
    </shelf>'
    
    SELECT  *,
            Cabinet.query('count(//item)').value('.','int')
    FROM    @Table