I found a solution for Oracle using UNION ALL on two hierarchical CONNECT BY queries, one representing ancestors and the other representing children.
I want to achieve the same value for DB2 and SQL Server .
I know one element, it can be a root, branch or leaf in the hierarchy. I need to get my whole hierarchy.
Suppose I have itemid = 'item3' and class = 'my class', I need to find his ancestors and children, I came up with:
with ancestor (class, itemid, parent, base, depth) as ( select root.class, root.itemid, root.parent, root.itemid, 0 from item root where root.class = 'myclass' and root.itemid = 'item3' -- union all -- select child.class, child.itemid, child.parent, root.base, root.depth+1 -- from ancestor root, item child -- where child.class = root.class -- and child.parent = root.itemid union all select parent.class, parent.itemid, parent.parent, parent.itemid, root.depth-1 from ancestor root, item parent where parent.class = root.class and parent.itemid = root.parent ) select distinct class, itemid, parent, base, depth from ancestor order by class, base, depth asc, itemid
I want to get the result as follows:
class itemid parent base depth myclass item1 null item3 -2 myclass item2 item1 item3 -1 myclass item3 item2 item3 0 myclass item4 item3 item3 1 myclass item5 item5 item3 2
If the above SQL is running, I get the ancestors in order. Now, if I delete comments, this seems like an endless loop. There must be a way to make this work.
I can get the results in the hierarchy in one direction (ancestor or children) in order, but I can not get both from the same query.
Has anyone ever tried something like this?
thanks