Pour construire le hieararchy vous avez besoin de « Stack » la requête d'une manière qui imite la hiérarchie que vous essayez de construire. Si vous utilisez une seule table ou un CTE pour construire votre XML, vous devez essayer de rendre les éléments "parents" distincts dans les appels sql. voir comment je distingue lors de la sélection des parents ci-dessous
Exemple:
use tempdb
GO
IF OBJECT_ID('tempdb..#ParentChild')IS NOT NULL DROP TABLE #ParentChild
CREATE TABLE #ParentChild(
ID int identity(1,1),
ParentID int,
ParentName varchar(25),
ChildName varchar(25));
Insert Into #ParentChild
Values(1,'John','Mike');
Insert Into #ParentChild
Values(1,'John','Russ');
Insert Into #ParentChild
Values(1,'John','Stan');
Select
pc.ParentName AS '@parent',
(Select
p.ChildName as '@child'
From #ParentChild p
Where p.ParentID = pc.ParentID
FOR XML PATH('children'),TYPE)
From (Select Distinct ParentID,ParentName
From #ParentChild) pc
FOR XML PATH('parent'),TYPE
DROP TABLE #ParentChild;
Visitez http://msdn.microsoft.com/en-us/library/ms345137(SQL.90).aspx et recherche " Recursion et FOR XML " – Andomar