Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count occurrences of a node in SQL XML?

I am trying to do a count on the number of occurrences of the "Colors" node but have been so far unsuccessful.

Below is what I have tried so far.

If I have the following logic:

DECLARE @MyXML XML
SET @MyXML = '<SampleXML>
<Colors>
<Color1>White</Color1>
<Color2>Blue</Color2>
<Color3>Black</Color3>
<Color4 Special="Light">Green</Color4>
<Color5>Red</Color5>
</Colors>
<Fruits>
<Fruits1>Apple</Fruits1>
<Fruits2>Pineapple</Fruits2>
<Fruits3>Grapes</Fruits3>
<Fruits4>Melon</Fruits4>
</Fruits>
</SampleXML>'

SELECT
count(a.b.value('Colors','varchar(10)')) AS Color1
FROM @MyXML.nodes('SampleXML') a(b)

I get the following error:

Msg 2389, Level 16, State 1, Line 50
XQuery [value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'

like image 576
some_bloody_fool Avatar asked Sep 25 '12 16:09

some_bloody_fool


People also ask

How do I count nodes in XML?

Count the XML elements (XPath)newXPath(); NodeList nodes = (NodeList) xpath. evaluate("//staff", doc, XPathConstants. NODESET); int count = nodes. getLength();


2 Answers

This will count the number of Colors nodes which is 1.

select @MyXML.value('count(/SampleXML/Colors)', 'int')

This will count the number of rows in Colors which is 5.

select @MyXML.value('count(/SampleXML/Colors/*)', 'int')
like image 179
Mikael Eriksson Avatar answered Sep 17 '22 14:09

Mikael Eriksson


select @MyXML.value('count(/SampleXML/Colors)', 'INT') AS 'Count'
like image 43
Anshu Avatar answered Sep 16 '22 14:09

Anshu