将层次表转换为桥

时间:2015-01-20 12:04:06

标签: sql sql-server-2008 tsql

我有这张原始表:

IF OBJECT_ID('tempdb..#Hierarchies') IS NOT NULL DROP TABLE #Hierarchies

CREATE TABLE #Hierarchies
    (
      [HierarchyId] [INT] NOT NULL ,
      [HierarchyName] NVARCHAR(MAX),
      [ParentHierarchyId] [INT]
        CONSTRAINT [PK_Hierarchies]
        PRIMARY KEY CLUSTERED ( [HierarchyId] ASC )
        WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
               IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
               ALLOW_PAGE_LOCKS = ON )
    )
ON  [PRIMARY]

INSERT INTO #Hierarchies ([HierarchyId], [HierarchyName], [ParentHierarchyId])
SELECT 1 , 'A', NULL
UNION ALL
SELECT 2 , 'B', 1
UNION ALL
SELECT 3 , 'C', 1
UNION ALL
SELECT 4 , 'D', 2

SELECT * FROM #Hierarchies

SELECT 
    b.HierarchyId,
    a.HierarchyId
FROM #Hierarchies a
CROSS JOIN
 #Hierarchies b
 ORDER BY b.HierarchyId

并希望将其转换为以下格式:

ParentId    ChildId LevelsRemoved
1   1   0
1   2   1
1   3   1
1   4   2
2   2   0
2   4   1
3   3   0

在我尝试实现这个轮子之前,我想知道是否有人可以如此友善并指出我现有的sql脚本?感谢。

1 个答案:

答案 0 :(得分:0)

我没理解你为什么要避免CTE。这是CTE的解决方案。

WITH Descendant AS(
   SELECT HierarchyId AS ParentId, HierarchyId As ChildId, 0 AS LevelsRemoved
   FROM #Hierarchies

   UNION ALL

   SELECT D.ParentId, H.HierarchyId AS ChildId, D.LevelsRemoved + 1 AS LevelsRemoved
   FROM Descendant D
   JOIN Hierarchies H ON D.ChildId = H.ParentHierarchyId
)
SELECT * FROM Descendant