Here are some sample records
ID(UniqueIdentifier) UserId title description version parentid
8362AB94-946F-4092-97C2-ABD957CC2E20 3 title desc 0 0
C4E3FCC1-49B5-4310-931F-B8EE48B3F38E 3 title2 desc2 0 1 8362AB94-946F-4092-97C2-ABD957CC2E20
C622113B-C6E6-4ED1-B727-E4F864643CD2 3 title3 desc3 0 2 8362AB94-946F-4092-97C2-ABD957CC2E20
Records represent a hierarchical edits of textual data. Such as , on saving a edit of ParentBoard a new entry is made and with incremental version number i.e 1,2(this all happens on application).
The columns of interest here are
ID - Unique Identifier
ParentId - NVARCHAR(50)
I am trying to build a xml as follows
<Edits>
<Id>314BA459-3749-4BC1-8AA4-E72B882539F5</Id>
<Title>Parent Title</Title>
<Description>Parent Description</Description>
<Version>0</Version>
<ParentId></ParentId>
<SubBoardCount>2</SubBoardCount>
</Edits>
Query
SELECT
Id 'Id',
Title 'Title',
[Description] 'Description',
Version 'Version',
ParentId 'ParentId',
(select COUNT(*) WHERE ParentId = (CAST(Id AS NVARCHAR(50)))) 'SubBoardCount',
FROM Edits
WHERE ParentId IS NULL OR ParentId = ''
FOR XML PATH('Edits')
Problem
Why do i always end up getting SubBoardCount as 0 rather than 2?
Because your “subquery” isn’t searching the table. Perhaps you meant:
Without the extra
FROM Edits e2clause, the references toParentIdandIdwithin the subquery were referencing those column values frome1(as I’ve now aliased it) and these aren’t ever equal.