查询获取给定root的所有子级和子级子级

时间:2016-12-09 09:25:48

标签: sql sql-server

我有如下所述的表格。 表名parentChildTable

         ------------------------------------
        |    ID     | Description |Parent ID|
        -------------------------------------
        |  1101     |  Root        | ''     |
        |  1102     | Child of 1101| 1101   |
        |  1105     | Child of 1101| 1101   |
        |  1103     | Child of 1102| 1102   |
        |  1104     | Child of 1102| 1102   |
        |  1178     | Child of 1105| 1105   |
        |  11440    | Child of 1105| 1105   |
        |  11567    | Childof 11440| 11440  |
        |  12904Y   | Child of11567| 11567  |
        |  125687   | Child of 1101| 1101   |

现在用1101 - > root作为参数我需要它的子和子子,直到无子级(我的意思是直到叶子)

示例输出应该是这样的

        ------------
        |    ID     |
        -------------
        |  1102     |
        |  1105     | 
        |  1103     |
        |  1104     |
        |  1178     |
        |  11440    |
        |  11567    |
        |  12904Y   |
        |  125687   |

提前感谢。

2 个答案:

答案 0 :(得分:1)

DECLARE @id VARCHAR(100)='1101'
;WITH tree(ID,Parent_ID)AS(
   SELECT '1101','' UNION
   SELECT '1102','1101' UNION
   SELECT '1105','1101' UNION
   SELECT '1103','1102' UNION
   SELECT '1104','1102' UNION
   SELECT '1178','1105' UNION
   SELECT '11440','1105' UNION
   SELECT '11567','11440' UNION
   SELECT '12904Y','11567' UNION
   SELECT '125687','1101' 
),cte AS(
   SELECT ID FROM tree WHERE ID=@id
   UNION ALL
   SELECT t.ID FROM tree AS t INNER JOIN  cte AS c ON  c.id=t.Parent_ID
)
SELECT * FROM cte WHERE cte.ID!=@ID
ORDER BY ID
ID
------
1102
1103
1104
1105
11440
11567
1178
125687
12904Y

答案 1 :(得分:1)

-- Set up test data
DECLARE @parentChildTable TABLE (
    ID VARCHAR(50),
    [Description] VARCHAR(50),
    [Parent ID] VARCHAR(50)
)

INSERT INTO @parentChildTable
SELECT '1101','Root',''
UNION
SELECT '1102','Child of 1101','1101'
UNION
SELECT '1105','Child of 1101','1101'
UNION
SELECT '1103','Child of 1102','1102'
UNION
SELECT '1104','Child of 1102','1102'
UNION
SELECT '1178','Child of 1105','1105'
UNION
SELECT '11440','Child of 1105','1105'
UNION
SELECT '11567','Childof 11440','11440'
UNION
SELECT '12904Y','Child of11567','11567'
UNION
SELECT '125687','Child of 1101','1101'

-- Set initial root (could switch this for any valid ID value)
DECLARE @rootID VARCHAR(50)
SET @rootID = '1101'

-- Iterate to find results
CREATE TABLE #results (
    ID VARCHAR(50),
    Searched BIT
)

DECLARE @currentRoot VARCHAR(50)
SET @currentRoot = @rootID

WHILE (@currentRoot IS NOT NULL)
BEGIN
    INSERT INTO #results
    SELECT ID, 0 FROM @parentChildTable WHERE [Parent ID] = @currentRoot
    UPDATE #results SET Searched = 1 WHERE ID = @currentRoot
    SELECT @currentRoot = MIN(ID) FROM #results WHERE Searched = 0
END

SELECT ID FROM #results

DROP TABLE #results

结果:

ID
------
1102
1105
125687
1103
1104
11440
1178
11567
12904Y