This is the link I used to find the solution.
http://wiki.lessthandot.com/index.php/Using_Common_Table_Expressions_for_Parent-Child_Relationships
EDIT - @Pshimo - thanks. Heres the guide forms a link.
Since SQL 2005, although this is a dream. Say you have data from this sample:
declare @test table (bunchof uniqueidentifier default newid(), columns uniqueidentifier default newid(), Id int, ParentID int) insert @test (Id, ParentId) select 1, null union all select 5, 1 union all select 15, 2 union all select 16, 5 union all select 27, 16
And you want to get all the child rows for 1 (so ItemId 5, 16, 27)
declare @parentId int set @parentId = 1 ;--last statement MUST be semicolon-terminated to use a CTE with CTE (bunchof, columns, Id, ParentId) as ( select bunchof, columns, Id, ParentId from @test where ParentId = @parentId union all select a.bunchof, a.columns, a.Id, a.ParentId from @test as a inner join CTE as b on a.ParentId = b.Id ) select * from CTE
and if you want to include the parent:
declare @Id int set @Id = 1 ;
You can also choose the depth in the hierarchy if you do these things:
declare @Id int set @Id = 1 ;
As you can see what you are doing here, first select your initial recordset containing all the child lines for the parent id parameter. Then you can combine in another query that joins the CTE itself to get the children-children (and their grandchildren, etc., until you reach the last line of the descendant. It is important to note that the default recursion limit is 100, so pay attention to the depth of your hierarchy when using them.You can change the recursion limit with OPTION (MAXRECURSION)
WITH CTE AS ( ... ) SELECT * FROM CTE OPTION (MAXRECURSION 1000)