SQL Server 2012 HierarchyId与两个父母?

时间:2014-02-07 15:40:13

标签: sql-server parent-child hierarchy common-table-expression hierarchyid

我有一个使用层次结构的工作系统,示例如下。我现在需要让一个孩子有两个父母,在我的例子中,我需要制作'番茄'(id = 4)水果和蔬菜。

我可以使用新的PK重组表格,然后复制番茄行,这样它就可以有 n 的rowid,并且仍然保留其“番茄标识符”,然后每行可以拥有自己的父级。 ...但是有没有另一种方法来指定多个父母而不重组整个表格?

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

感谢。

1 个答案:

答案 0 :(得分:1)

HierarchyId不是您的选择(或者至少不是一种自然的方式)。

点击此链接查看traversing hierarchies nodes with multiple parents