问题
XML sent from code to the SQL server. My XML as looks like this:
Declare @MainXML XML=
'<root>
<a>JJ</a>
<a>KK</a>
</root>'
From the above xml, I want to store 2 as being the count of child elements "a" under a column1 in SQL.
Column1
-------
2
Can you help me with this?
回答1:
I'd do this with xpath
:
select @MainXML.query('count(root/a)')
sql fiddle demo
回答2:
If you're using mssql server
then you can take advantage of the OPENXML support. You can get the count of the a
nodes by using a SELECT
on the parsed XML:
Declare @MainXML XML =
'<root>
<a>JJ</a>
<a>KK</a>
</root>'
SELECT COUNT(MainXML.A.value('.', 'VARCHAR(100)')) AS Cnt
FROM @MainXML.nodes('root/a') MainXML(A)
来源:https://stackoverflow.com/questions/30132560/count-the-number-of-sub-tags-from-xml-in-sql