I have the following table and values:
create table TreeTable (
ID int primary key,
ParentID int not null,
Name varchar(255) not null
)
insert into TreeTable([ID], [ParentID], [Name]) values
(1, 0, 'rootA'),
(2, 1, 'rootAchildA'),
(3, 1, 'rootAchildB'),
(4, 2, 'rootAchildAchildA'),
(5, 2, 'rootAchildAchildB'),
(6, 3, 'rootAchildBchildA'),
(7, 3, 'rootAchildBchildB');
(8, 0, 'rootB'),
(9, 8, 'rootBchildA'),
(10, 8, 'rootBchildB');
I want to write a T-SQL statement that will return all children of each root with the root ID; that is,
[Name] [RootID]
'rootAchildA' 1
'rootAchildB' 1
'rootAchildAchildA' 1
'rootAchildAchildB' 1
'rootAchildBchildA' 1
'rootAchildBchildB' 1
'rootBchildA' 8
'rootBchildB' 8
The depth of the tree may be arbitrarily long. What statement will return this?
I’ve deliberately over generalised this so that it might be useful on more situations.