In SQL Server 2005 and later, it is best to use a recursive CTE (generic table expression) for this kind of query. (in SQL 2000 and earlier, you were limited to using a recursive stored procedure).
Something like the following that you need:
WITH ParentChildRels (ParentId, ChildId, KeyField, HierarchyLevel) AS ( -- Base case SELECT ParentId, ChildId, KeyField, 1 as HierarchyLevel FROM Records WHERE ChildId = @ChildId UNION ALL -- Recursive step SELECT r.ParentId, r.ChildId, r.KeyField, pr.HierarchyLevel + 1 AS HierarchyLevel FROM Records r INNER JOIN ParentChildRels pr ON r.ParentId = pr.ParentId ) SELECT * FROM ParentChildRels ORDER BY HierarchyLevel, ParentId, ChildId, KeyField
source share