4

Possible Duplicate:
Recursive function in sql server 2005?

How do you perform an iterative query on a table? I have a simple table which consists of a:

KeyField, childID, parentID

Starting with a childID, I want to pull the parentID and then query again to see if that parent (which is now the child) has its own parent, working up through the complete hierarchy, how do I do that?

Microsoft SQL Server, version number 09.00.3042

5
  • 1
    Take your pick of duplicates: stackoverflow.com/search?q=recursive+cte Commented Jan 8, 2010 at 5:51
  • 1
    Particularly: stackoverflow.com/questions/1709397/… Commented Jan 8, 2010 at 5:53
  • Yep, plenty of duplicates - although this is one of those annoying cases where unless one knows about recursive CTEs, one might not know the search terms to use. Commented Jan 8, 2010 at 5:54
  • I answered because I lack the rep to vote to close, and I wanted the practise at answering about CTEs. Hopefully some 3k+ people will close as duplicate. Commented Jan 8, 2010 at 6:02
  • Thanks OMG Ponies (love the name) and David, I obviously need to do a little reading and yes I have never heard of CTE's, but I have now :) Commented Jan 8, 2010 at 6:09

1 Answer 1

5

In SQL Server 2005 and later, you are best to use a recursive CTE (common table expression) for this sort of query. (in SQL 2000 and earlier you were limited to using a recursive stored procedure).

Something like the following is what 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
Sign up to request clarification or add additional context in comments.

1 Comment

The recursive WITH is ANSI standard for handling recursive queries, but support is limited. Oracle supports the recursive WITH in 11g, but the WITH is supported 9i+ and it has it's own hierarchical syntax.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.