I'm experimenting with CTE's in SQL Server but have reached a dead end with getting the following scenario to work. I have a hierarchy table similar to this:
Node(ID:439)
Node(ID:123)
Node(ID:900)
Node(ID:56)
Node(ID:900)
Expected results:
NodeID ParentNodeID
439 0
123 439
900 123
56 439
900 56
So basically we have a parent-child hierarchy table, with one subtle difference. Each child could potentially have more then one parent. I have researched many blog articles, and StackOverflow posts, about creating CTE's that return parent-child records, but they don't return all of the parents for the children, just the first one that it finds.
Here's an example CTE that I tried:
WITH Hierarchy(NodeID, ParentNodeID)
AS
(
SELECT
T1.NodeID,
T1.ParentNodeID
FROM
ParentChildTable T1
WHERE
T1.NodeID = 439
UNION ALL
SELECT
T1.NodeID,
T1.ParentNodeID
FROM
Heirarchy T1
INNER JOIN Heirarchy TH ON TH.NodeID = T1.ParentNodeID
)
(Note: The names of the tables and columns in the above CTE have been changed from the orginal for privacy purposes.)
The above CTE works fine, it finds all the parent-child records starting from ID:439, but it only finds one parent for item ID:900, even though it has two parents.
Could someone let me know if this is possible using CTE's, or is there another SQL way to do this?
Cheers. Jas.
This appears to work OK for me, once I corrected the syntax error in your CTE:
Returns the result:
This is the link I used to find a solution..
http://wiki.lessthandot.com/index.php/Using_Common_Table_Expressions_for_Parent-Child_Relationships
EDIT - @Pshimo - thanks. Heres the guide form the link.
With SQL 2005 though it is a dream. Say you have this sample data:
And you want to get all child rows for 1 (so ItemId 5, 16, 27)
and if you want to include the parent:
You can select depth in the hierarchy as well, if you're into that kind of thing:
As you can see what you're doing here is first selecting your initial recordset, which contains all child rows for your parent ID parameter. You can then union to another query that joins to the CTE itself, to get the children's children (and their grandchildren, and so forth until you reach the last descendant row. Its' important to note that the default recursion limit is 100, so pay attention to the depth of your hierarchy when using these. You can change the recursion limit using the OPTION (MAXRECURSION)