2010-03-08 187 views
2

我是新來查詢SQL Server 2005中的XML數據類型。任何人都可以幫我創建一個查詢我的需求?這是我的專欄的一個場景。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 

我想統計「項目」節點的數量,而不管其類型爲&顏色。提前致謝。

回答

2

看一看這個(全部工作示例

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 
+0

感謝,正是我需要的。 – hallie 2010-03-08 15:19:51

+0

這是一個很好的例子! – 2010-04-29 15:20:15