2016-09-24 110 views
-2

我有一個表是這樣的:查找孩子遞歸

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和結果列表我必須找到它的所有記錄id_menu s是20003, 20004, 20005

我該怎麼做?

回答

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 
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