2

I'm new to querying XML datatype in SQL Server 2005. Anyone can help me create a query for my requirement? Here's a scenario of my column.

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

I want to count the number of "item" nodes regardless of its type & color. Thanks in advance.

1 Answer 1

2

Have a look at this (Full working example)

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.