Obtenir le parent racine de l'enfant dans la table hiérarchique

J'ai une table avec des données hiérarchiques, la structure va comme ceci:

ID ParentId ---- ---------- 1 NULL 2 1 3 2 4 2 5 3 6 5 

Si je passe le nœud Id, je voudrais get le plus haut Id / détails du nœud en parcourant tous ses parents en SQL.

J'ai essayé CTE, je ne peux pas get la combinaison correcte. Cependant, j'ai travaillé en fonction, mais il est si lent que j'ai dû postr cette question.

Dans l'exemple ci-dessus, si je passe 6, je voudrais avoir le plus haut, c'est-à-dire 1. En passant par 6 => 5 => 3 => 2 => [1] (résultat)

Merci d'avance pour votre aide.

S'il vous plaît essayez:

 declare @id int=6 ;WITH parent AS ( SELECT id, parentId from tbl WHERE id = @id UNION ALL SELECT t.id, t.parentId FROM parent INNER JOIN tbl t ON t.id = parent.parentid ) SELECT TOP 1 id FROM parent order by id asc 
 DECLARE @id INT = 6 ;WITH parent AS ( SELECT id, parentId, 1 AS [level] from tbl WHERE id = @id UNION ALL SELECT t.id, t.parentId, [level] + 1 FROM parent INNER JOIN tbl t ON t.id = parent.parentid ) SELECT TOP 1 id FROM parent ORDER BY [level] DESC 

@ La réponse de TechDo suppose que l'ID le plus bas sera le parent. Si vous ne voulez pas countr sur cela alors la requête ci-dessus va sortinger par la profondeur.

 ;WITH CTE as ( Select I.ID,P.Parent_id from #temp I join #temp P on P.Id = I.Parent_Id where i.ID = 6 union all Select I.ID,P.Parent_id from CTE I join #temp P on P.Id = I.Parent_Id where p.Parent_Id is not null ) Select ID,min(parent_id) from CTE group by id; 

Vous pouvez essayer cette requête mon ami pour get tous les identifiants:

 with tab1(ID,Parent_ID) as (select * from table1 where id = 6 union all select t1.* from table1 t1,tab1 where tab1.Parent_ID = t1.ID) select ID from tab1; 

et cette requête donnera le résultat final:

 with tab1(ID,Parent_ID) as (select * from table1 where id = 6 union all select t1.* from table1 t1,tab1 where tab1.Parent_ID = t1.ID) select ID from tab1 where parent_id is null; 

SQL Fiddle