Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 CTE: Union hierarchy tables by more roots id

Author  Topic 

waltz
Starting Member

1 Post

Posted - 2013-10-04 : 05:52:54
Hi Masters,

i try to build some query on hierarchy data and after two days thinking about it i have null result :( what i need is union more trees tables by root id to one table. Can you help me ?


-- tree
-- this query is functional: OK
WITH tree (sid, parend_id, level) as
(
SELECT sid, parend_id, 0 as level
FROM table1
WHERE parent_id = 100 -- root (id)

UNION ALL

SELECT c2.sid, c2.parent_id, tree.level + 1
FROM table1 c2
INNER JOIN tree ON tree.sid = c2.parent_id
)


..but this query work with one root id (100); what can i do when i have moore roots id ? -> generate each tree table separated by roots id and then all tables join to one (union).

Uff ..I hope this is understandable :)

Thank you so mutch for help

Waltz

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-10-04 : 07:33:57
Assuming root nodes will have parent_id as null you can use something like


-- tree
WITH tree (sid, parend_id, level) as
(
SELECT sid, parend_id, 0 as level
FROM table1
WHERE parent_id is null-- all roots

UNION ALL

SELECT c2.sid, c2.parent_id, tree.level + 1
FROM table1 c2
INNER JOIN tree ON tree.sid = c2.parent_id
)

SELECT *
FROM tree
OPTION (MAXRECURSION 0)


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -