Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A self-referential representation of hierarchy is a bit clunky for jobs like - you want to select only one branch, so you'll need to recursively join onto the target table an unknown number of times. Very possible, but any time I work with hierarchies in SQL Server I jump straight to the <a href="http://technet.microsoft.com/en-us/library/bb677290.aspx" rel="nofollow">HierarchyId</a>.</p> <p>I don't know if we can recursively look both <em>up</em> and <em>down</em> the tree at the same time; a naive approach fails for me, so I'll present a simpler alternative.</p> <p>You already have the current node. Get the children of that node, and then get the parents of that node. Union them and you're done. And the easiest way to do recursive joins in SQL is with <a href="http://msdn.microsoft.com/en-us/library/ms186243.aspx" rel="nofollow">Common Table Expressions</a>.</p> <pre><code>DECLARE @nodeid INT = 4 DECLARE @nodes TABLE (NodeID INT) ; WITH Parents (NodeID) AS ( -- get the parent of the current node SELECT FK_ParentNodeID FROM NodeHierarchy WHERE PK_NodeID = @nodeId -- not sure if 'null' is a valid parent, but I'm assuming not AND FK_ParentNodeID IS NOT NULL UNION ALL -- recursively get the parents of the parent SELECT FK_ParentNodeID FROM NodeHierarchy INNER JOIN Parents ON PK_NodeID = NodeID WHERE FK_ParentNodeID IS NOT NULL ) INSERT @nodes SELECT NodeID FROM Parents ; WITH Childs (NodeID) AS ( -- selecting the current node SELECT PK_NodeID FROM NodeHierarchy WHERE PK_NodeID = @nodeId UNION ALL -- recursively select the children of the branch SELECT PK_NodeID FROM NodeHierarchy INNER JOIN Childs ON FK_ParentNodeID = NodeID ) INSERT @nodes SELECT NodeID FROM Childs SELECT * FROM @nodes </code></pre> <p>Now based on your previous question, you simply need to select from your existing views.</p> <pre><code>SELECT Node, Label FROM NodeLabels WHERE Node IN (SELECT NodeID FROM @nodes) SELECT Parent, Child FROM Edges WHERE Parent IN (SELECT NodeID FROM @nodes) </code></pre>
    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. This table or related slice is empty.
    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