如何在XML变量中获取特定元素Count

时间:2012-01-06 19:17:30

标签: sql-server xml sql-server-2008 tsql

考虑这个XML:

<Employees>
    <Person>
        <ID>1000</ID>
        <Name>Nima</Name>
        <LName>Agha</LName>
    </Person>
    <Person>
        <ID>1001</ID>
        <Name>Ligha</Name>
        <LName>Ligha</LName>
    </Person>
    <Person>
        <ID>1002</ID>
        <Name>Jigha</Name>
        <LName>Jigha</LName>
    </Person>
    <Person>
        <ID>1003</ID>
        <Name>Aba</Name>
        <LName>Aba</LName>
    </Person>
</Employees>

我声明了一个XML变量并将此XML分配给它。如何使用Sql Server 2008(TSQL)获取此XML变量中ID个元素的数量?

2 个答案:

答案 0 :(得分:16)

SELECT @XMLVariable.value('count(/Employees/Person/ID)', 'int') AS IDCount

答案 1 :(得分:4)

试试这个:

declare @xmlvar XML;
set @xmlvar ='<YOUR XML>';
select @xmlvar.value('count(/Employees/Person/ID)', 'INT') AS 'Count'