Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Can't you do something like this?</p> <pre><code>;WITH cte AS (....) SELECT * FROM cte CROSS APPLY dbo.myTable tbl ON cte.XXX = tbl.XXX </code></pre> <p>Put the <code>CROSS APPLY</code> <strong>after</strong> the CTE definition - into the one SQL statement that refers back to the CTE. Wouldn't that work??</p> <p><strong>OR:</strong> - flip around your logic - do a "top-down" CTE, that picks the top-level nodes first, and then iterates through the hiearchy. This way, you can easily determine the "top-level father" in the first part of the recursive CTE - something like this:</p> <pre><code>;WITH ChildParent AS ( SELECT ID, ParentID = ISNULL(ParentID, -1), SomeName, PLevel = 1, -- defines level, 1 = TOP, 2 = immediate child nodes etc. TopLevelFather = ID -- define "top-level" parent node FROM dbo.[Agent_Agents] WHERE ParentID IS NULL UNION ALL SELECT a.ID, ParentID = ISNULL(a.ParentID, -1), a.SomeName, PLevel = cp.PLevel + 1, cp.TopLevelFather -- keep selecting the same value for all child nodes FROM dbo.[Agent_Agents] a INNER JOIN ChildParent cp ON r.ParentID = cp.ID ) SELECT ID, ParentID, SomeName, PLevel, TopLevelFather FROM ChildParent </code></pre> <p>This would give you nodes something like this (based on your sample data, slightly extended):</p> <pre><code>ID ParentID SomeName PLevel TopLevelFather 20 -1 Top#20 1 20 4 -1 TOP#4 1 4 8 -1 TOP#8 1 8 7 8 ChildID = 7 2 8 3 7 ChildID = 3 3 8 2 4 ChildID = 2 2 4 9 20 ChildID = 9 2 20 5 9 ChildID = 5 3 20 1 5 ChildID = 1 4 20 </code></pre> <p>Now if you select a particular child node from this CTE output, you'll always get all the infos you need - including the "level" of the child, and its top-level parent node.</p>
    singulars
    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.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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