1. Learn
  2. /
  3. Courses
  4. /
  5. Hierarchical and Recursive Queries in SQL Server

Exercise

Get the number of generations?

In this exercise, we are going to look at a random family tree. The dataset family consists of three columns, the ID, the name, and the ParentID. Your task is to calculate the number of generations. You will do this by counting all generations starting from the person with ParentID = 101.

For this task, you have to calculate the LEVEL of the recursion which represents the current level in the generation hierarchy. After that, you need to count the number of LEVELs by using COUNT(). Recall that the count of level is the number of generations, for example, a level count of 100 means you found 100 generations.

Instructions

100 XP
  • Initialize the recursion start by setting the ParentID to 101.
  • Set LEVEL to the current recursion step.
  • Join the anchor member to the CTE on the ID of the parent and the child.
  • COUNT() the number of generations.