Count the number of sub tags from XML in SQL

拜拜、爱过 提交于 2019-12-08 02:36:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!