I'm going to assume that you are inserting valid XML into the column and not what you have shown us so far.
I created a sample table like this:
CREATE TABLE test (id int identity(1,1), xmlcol XML)
insert into test values
('<Agreements>
<MyAgreement>
<Status>n</Status>
<Au>000100U1</Au>
<PKey>2yk0000000056f3a</PKey>
<HKey>2yk0000000056f3a</HKey>
<BusinessModified>2012-04-06 19:04:51</BusinessModified>
<MyActive>1</MyActive>
</MyAgreement>
<MyAgreement>
<Status>n</Status>
<Au>000100U1</Au>
<PKey>2yk0000000056f3b</PKey>
<HKey>2yk0000000056f3b</HKey>
<BusinessModified>2012-04-06 19:04:51</BusinessModified>
<MyActive>1</MyActive>
</MyAgreement>
</Agreements>
'),
('<Agreements>
<MyAgreement>
<Status>n</Status>
<Au>000100U1</Au>
<PKey>4yk0000000056f3a</PKey>
<HKey>4yk0000000056f3a</HKey>
<BusinessModified>2012-04-07 19:04:51</BusinessModified>
<MyActive>1</MyActive>
</MyAgreement>
<MyAgreement>
<Status>n</Status>
<Au>000100U1</Au>
<PKey>4yk0000000056f3b</PKey>
<HKey>4yk0000000056f3b</HKey>
<BusinessModified>2012-04-07 19:04:51</BusinessModified>
<MyActive>1</MyActive>
</MyAgreement>
</Agreements>
')
Note that I'm assuming the root node to the XML is
Agreements
- change that in the query if it is wrong.
You can get all of the
PKey
nodes listed with this query:
select id,
n.x.value('PKey[1]', 'VARCHAR(25)') AS [pkey]
FROM test
CROSS APPLY xmlcol.nodes('/Agreements/MyAgreement') n(x)
So to get the count of
PKey
nodes put that into a sub-query thus:
select id, count(*) from
(
select id,
n.x.value('PKey[1]', 'VARCHAR(25)') AS [pkey]
FROM test
CROSS APPLY xmlcol.nodes('/Agreements/MyAgreement') n(x)
) as q
group by id
There are a number of articles available on querying XML columns in SQL Server, here is one of them:
XML Workshop[
^]