Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>here is a boiler plate (not based on the given OP's code) example of a recursive tree CTE, which shows how to sort a tree:</p> <pre><code>DECLARE @Contacts table (id varchar(6), first_name varchar(10), reports_to_id varchar(6)) INSERT @Contacts VALUES ('1','Jerome', NULL ) -- tree is as follows: INSERT @Contacts VALUES ('2','Joe' ,'1') -- 1-Jerome INSERT @Contacts VALUES ('3','Paul' ,'2') -- / \ INSERT @Contacts VALUES ('4','Jack' ,'3') -- 2-Joe 9-Bill INSERT @Contacts VALUES ('5','Daniel','3') -- / \ \ INSERT @Contacts VALUES ('6','David' ,'2') -- 3-Paul 6-David 10-Sam INSERT @Contacts VALUES ('7','Ian' ,'6') -- / \ / \ INSERT @Contacts VALUES ('8','Helen' ,'6') -- 4-Jack 5-Daniel 7-Ian 8-Helen INSERT @Contacts VALUES ('9','Bill ' ,'1') -- INSERT @Contacts VALUES ('10','Sam' ,'9') -- DECLARE @Root_id varchar(6) --get all nodes 2 and below SET @Root_id=2 PRINT '@Root_id='+COALESCE(''''+@Root_id+'''','null') ;WITH StaffTree AS ( SELECT c.id, c.first_name, c.reports_to_id, c.reports_to_id as Manager_id, cc.first_name AS Manager_first_name, 1 AS LevelOf FROM @Contacts c LEFT OUTER JOIN @Contacts cc ON c.reports_to_id=cc.id WHERE c.id=@Root_id OR (@Root_id IS NULL AND c.reports_to_id IS NULL) UNION ALL SELECT s.id, s.first_name, s.reports_to_id, t.id, t.first_name, t.LevelOf+1 FROM StaffTree t INNER JOIN @Contacts s ON t.id=s.reports_to_id WHERE s.reports_to_id=@Root_id OR @Root_id IS NULL OR t.LevelOf&gt;1 ) SELECT * FROM StaffTree ORDER BY LevelOf, first_name </code></pre> <p>OUTPUT:</p> <pre><code>@Root_id='2' id first_name reports_to_id Manager_id Manager_first_name LevelOf ------ ---------- ------------- ---------- ------------------ ----------- 2 Joe 1 1 Jerome 1 6 David 2 2 Joe 2 3 Paul 2 2 Joe 2 5 Daniel 3 3 Paul 3 8 Helen 6 6 David 3 7 Ian 6 6 David 3 4 Jack 3 3 Paul 3 (7 row(s) affected) </code></pre> <p>The key is the <code>LevelOf</code> column. See how it is just a literal <code>1</code> when selecting the main parent in the CTE. The <code>LevelOf</code> column is then incremented in the <code>UNION ALL</code> portion of the recursive CTE. Each recursive call (not row) to the CTE will hit that <code>UNION ALL</code> one time and the increment. Not a whole lot more to it than that. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload