递归地找孩子

时间:2016-09-24 09:34:01

标签: sql sql-server tsql recursive-query

我有一张这样的表:

enter image description here 创作脚本:

CREATE #TableName TABLE (
    Id int, 
    Id_Group int, 
    Id_Menu int
)
INSERT INTO #TableName VALUES
(1, 20005, 1014),(2, 20003, 1054),(3, 20005, 1058),
(4, 20004, 1055),(5, 20004, 1056),(6, 20004, 1057),
(7, 20003, 1053),(8, 1014, 0),(9, 20003, 1014),
(10, 20003, 1052),(11, 20003, 1164),(12, 20003, 1065),
(13, 20003, 1066),(14, 20003, 1067),(15, 20003, 1068),
(16, 20004, 1014),(17, 50100, 20003),(18, 50200, 20003),
(19, 50100, 20004),(20, 50200, 20004),(21, 50100, 20005),
(22, 50200, 20005)

我得到Id_Menu例如1014它必须找到其id_menu必须等于1014的记录,结果为20003, 20004, 20005,结果列表I必须找到id_menu20003, 20004, 20005等的所有记录

我该怎么做?

2 个答案:

答案 0 :(得分:1)

递归CTE可以帮到你:

DECLARE @var int = 1014

;WITH rec AS (
SELECT  Id, 
        Id_Group, 
        Id_Menu,
        1 as [level]
FROM YourTable
WHERE Id_Group = @var
UNION ALL
SELECT  y.Id,
        y.Id_Group,
        y.Id_Menu,
        r.[level]+1
FROM YourTable y
INNER JOIN rec r
    ON r.Id_Group = y.Id_Menu
)

SELECT *
FROM rec

输出:

Id  Id_Group    Id_Menu level
8   1014        0       1
1   20005       1014    2
9   20003       1014    2
16  20004       1014    2
19  50100       20004   3
20  50200       20004   3
17  50100       20003   3
18  50200       20003   3
21  50100       20005   3
22  50200       20005   3

答案 1 :(得分:0)

可能会有人帮忙

; with CTE as(
select Id_Group from YourTable where Id_Menu=1014)
select c.Id_Group,y.Id_Menu from CTE c with(nolock) join YourTable y with(nolock) on c.Id_Group=y.Id_Group