Multiple parents tree (or digraph) implementation sql server 2005

前端 未结 3 1943
遥遥无期
遥遥无期 2021-01-03 11:37

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

3条回答
  •  既然无缘
    2021-01-03 12:27

    If you want to use all root objects as starting objects, you should first update your data to include information about the root objects (and the leaves). You should add the following inserts:

    insert into #ObjectRelations values (NULL, 'G')
    insert into #ObjectRelations values (NULL, 'A')
    insert into #ObjectRelations values ('X', NULL)
    insert into #ObjectRelations values ('F', NULL)
    

    Of course you could also write your anchor query in such a way that you select as root nodes the records that have an Id that does not occur as a NextId, but this is easier.

    Next, modify your anchor query to look like this:

    SELECT rel.Id,
           rel.NextId
    FROM #ObjectRelations rel
    WHERE rel.Id IS NULL
    

    If you run this query, you'll see that you get a lot of duplicates, a lot of arcs occur multiple times. This is because you now have two results from your anchor query and therefore the tree is traversed two times.

    This can be fixed by changing your select statement to this (note the DISTINCT):

    SELECT DISTINCT o.*
    FROM   Objects o
    

提交回复
热议问题