Question

I have a working system that uses a hierarchy, sample is below. I now need to make a child have two parents, in my example I need to make 'tomato' (id=4) both a fruit and a vegetable.

I could restructure the table with a new PK and then duplicate the tomato row so it could have rowid of n and still keep its 'tomato identifier' and then each row could have its own parent.... But is there another way to specify multiple parents without restructuring the whole table?

DECLARE @hierdest TABLE
    (
      id INT PRIMARY KEY ,
      parentid INT ,
      name VARCHAR(24) ,
      hier HIERARCHYID
    )
DECLARE @hierorig TABLE
    (
      id INT PRIMARY KEY ,
      parentid INT ,
      name VARCHAR(24)
    )
INSERT  INTO @hierorig
        SELECT  1 ,
                0 ,
                'root'
        UNION ALL
        SELECT  2 ,
                1 ,
                'fruit'
        UNION ALL
        SELECT  3 ,
                1 ,
                'vegetable'
        UNION ALL
        SELECT  4 ,
                2 ,
                'tomato'
        UNION ALL
        SELECT  5 ,
                1 ,
                'apple'  
DECLARE @childtemp TABLE
    (
      id INT ,
      parentid INT ,
      num INT
    ) 
INSERT  @childtemp
        ( id ,
          parentid ,
          num 
        )
        SELECT  id ,
                parentid ,
                ROW_NUMBER() OVER ( PARTITION BY parentid ORDER BY parentid )
        FROM    @hierorig;
WITH    paths ( path, id )
          AS ( SELECT   HIERARCHYID::GetRoot() AS hier ,
                        id
               FROM     @childtemp AS c
               WHERE    parentid = 0
               UNION ALL
               SELECT   CAST(p.path.ToString() + CAST(c.num AS VARCHAR(30))
                        + '/' AS HIERARCHYID) ,
                        c.id
               FROM     @childtemp AS c
                        JOIN paths AS p ON c.parentid = p.id
             )
    INSERT  @hierdest
            ( hier ,
              o.id ,
              o.name ,
              o.parentid 
            )
            SELECT  p.path ,
                    o.id ,
                    o.name ,
                    o.parentid
            FROM    @hierorig AS o
                    JOIN paths AS p ON o.id = p.id

DECLARE @vertcurrent HIERARCHYID = ( SELECT hier
                                     FROM   @hierdest
                                     WHERE  id = 1
                                   )
SELECT  hier.ToString() AS hiernode ,
        *
FROM    @hierdest
WHERE   hier.IsDescendantOf(@vertcurrent) = 1
ORDER BY hier

Thanks.

Was it helpful?

Solution

HierarchyId is not an option in your case (or at least is not a natural way to do it).

Check this link for traversing hierarchies nodes with multiple parents.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top