Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 226669
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T19:32:03+00:00 2026-05-11T19:32:03+00:00

I need to implement a multi-parented tree (or digraph) onto SQL Server 2005. I’ve

  • 0

I need to implement a multi-parented tree (or digraph) onto SQL Server 2005.
I’ve read several articles, but most of them uses single-parented trees with a unique root like the following one.

-My PC
   -Drive C
      -Documents and Settings
      -Program Files
         -Adobe
         -Microsoft
      -Folder X
   -Drive D
      -Folder Y
      -Folder Z

In this one, everything derives from a root element (My PC).

In my case, a child could have more than 1 parent, like the following:

G  A
 \ /
  B
 / \ 
X   C
  /  \
  D   E
  \ /
   F

So I have the following code:

create table #ObjectRelations
(
    Id varchar(20),
    NextId varchar(20)
)

insert into #ObjectRelations values ('G', 'B')
insert into #ObjectRelations values ('A', 'B') 
insert into #ObjectRelations values ('B', 'C')
insert into #ObjectRelations values ('B', 'X')
insert into #ObjectRelations values ('C', 'E') 
insert into #ObjectRelations values ('C', 'D') 
insert into #ObjectRelations values ('E', 'F') 
insert into #ObjectRelations values ('D', 'F') 

declare @id varchar(20)
set @id = 'A';

WITH Objects (Id, NextId) AS
( -- This is the 'Anchor' or starting point of the recursive query
  SELECT rel.Id,
         rel.NextId
    FROM #ObjectRelations rel
   WHERE rel.Id = @id
   UNION ALL -- This is the recursive portion of the query
  SELECT rel.Id,
         rel.NextId
    FROM #ObjectRelations rel
   INNER JOIN Objects -- Note the reference to CTE table name (Recursive Join)
      ON rel.Id = Objects.NextId
)
SELECT  o.*
FROM    Objects o

drop table #ObjectRelations

Which returns the following SET:

Id                   NextId
-------------------- --------------------
A                    B
B                    C
B                    X
C                    E
C                    D
D                    F
E                    F

Expected result SET:

Id                   NextId
-------------------- --------------------
G                    B
A                    B
B                    C
B                    X
C                    E
C                    D
D                    F
E                    F

Note that the relation G->B is missing, because it asks for an starting object (which doesn’t work for me also, because I don’t know the root object from the start) and using A as the start point will ignore the G->B relationship.

So, this code doesn’t work in my case because it asks for a starting object, which is obvious in a SINGLE-parent tree (will always be the root object). But in multi-parent tree, you could have more than 1 “root” object (like in the example, G and A are the “root” objects, where root is an object which doesn’t have a parent (ancestor)).

So I’m kind of stucked in here… I need to modify the query to NOT ask for a starting object and recursively traverse the entire tree.
I don’t know if that’s possible with the (Id, NextId) implementation… may be I need to store it like a graph using some kind of Incidence matrix, adjacency matrix or whatever (see http://willets.org/sqlgraphs.html).

Any help? What do you think guys?
Thank you very much for your time =)

Cheers!

Sources:
Source 1
Source 2
Source 3

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T19:32:04+00:00Added an answer on May 11, 2026 at 7:32 pm

    Well, I finally came up with the following solution.
    It’s the way I found to support multi-root trees and also cycling digraphs.

    create table #ObjectRelations
    (
        Id varchar(20),
        NextId varchar(20)
    )
    
    /* Cycle */
    /*
    insert into #ObjectRelations values ('A', 'B')
    insert into #ObjectRelations values ('B', 'C') 
    insert into #ObjectRelations values ('C', 'A')
    */
    
    /* Multi root */
    
    insert into #ObjectRelations values ('G', 'B')
    insert into #ObjectRelations values ('A', 'B') 
    insert into #ObjectRelations values ('B', 'C')
    insert into #ObjectRelations values ('B', 'X')
    insert into #ObjectRelations values ('C', 'E') 
    insert into #ObjectRelations values ('C', 'D') 
    insert into #ObjectRelations values ('E', 'F') 
    insert into #ObjectRelations values ('D', 'F') 
    
    
    declare @startIds table
    (
        Id varchar(20) primary key
    )
    
    ;WITH 
        Ids (Id) AS
        (
            SELECT  Id
            FROM    #ObjectRelations
        ),
        NextIds (Id) AS
        (
            SELECT  NextId
            FROM    #ObjectRelations
        )
    INSERT INTO @startIds
    /* This select will not return anything since there are not objects without predecessor, because it's a cyclic of course */
    SELECT DISTINCT
        Ids.Id
    FROM
        Ids
    LEFT JOIN
        NextIds on Ids.Id = NextIds.Id
    WHERE
        NextIds.Id IS NULL
    UNION
    /* So let's just pick anyone. (the way I will be getting the starting object for a cyclic doesn't matter for the regarding problem)*/
    SELECT TOP 1 Id FROM Ids
    
    ;WITH Objects (Id, NextId, [Level], Way) AS
    ( -- This is the 'Anchor' or starting point of the recursive query
      SELECT rel.Id,
             rel.NextId,
             1,
             CAST(rel.Id as VARCHAR(MAX))
        FROM #ObjectRelations rel
       WHERE rel.Id IN (SELECT Id FROM @startIds)
    
       UNION ALL -- This is the recursive portion of the query
    
      SELECT rel.Id,
             rel.NextId,
             [Level] + 1,
             RecObjects.Way + ', ' + rel.Id
        FROM #ObjectRelations rel
       INNER JOIN Objects RecObjects -- Note the reference to CTE table name (Recursive Join)
          ON rel.Id = RecObjects.NextId
       WHERE RecObjects.Way NOT LIKE '%' + rel.Id + '%'
    
    )
    SELECT  DISTINCT 
            Id,
            NextId,
            [Level]
    FROM    Objects
    ORDER BY [Level]
    
    drop table #ObjectRelations
    

    Could be useful for somebody. It is for me =P
    Thanks

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 160k
  • Answers 160k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Delegates are not for properties. However, Reflection is slow, may… May 12, 2026 at 11:35 am
  • Editorial Team
    Editorial Team added an answer Something like this should work: insert into TableName(DateColumn) select convert(datetime,getDate(),103) May 12, 2026 at 11:35 am
  • Editorial Team
    Editorial Team added an answer First, edit the .sql file's properties so that it will… May 12, 2026 at 11:35 am

Related Questions

I need to implement a multi-parented tree (or digraph) onto SQL Server 2005. I've
Is it possible to implement a multi-threaded class loader in Java? In a meta-driven
I am developing a scientific application used to perform physical simulations. The algorithms used
I’m starting a project where I need to implement a light-weight interpreter. The interpreter
The App I need to implement a web app that will be used by

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.