Here is a working example:
declare @t table (id int, name nvarchar(255), ParentID int) insert @t values (1, 'TestName1', NULL), (2, 'TestName2', 1 ), (3, 'TestName3', 2 ), (4, 'TestName4', NULL), (5, 'TestName5', 1 ); ; with rec as ( select t.name , t.id as baseid , t.id , t.parentid from @tt union all select t.name , r.baseid , t.id , t.parentid from rec r join @tt on t.ParentID = r.id ) select * from rec where baseid = 1
You can filter by baseid , which contains the beginning of the tree you are requesting.
Andomar
source share