2013-10-04 123 views
0

我有如下表:SQL Server查詢選擇父母與特定的孩子

ID  Emp_Name  Manager_ID 
101  Ken   NULL 
102  Terri  101 
103  Roberto  101 
104  Rob   102 
105  Gail   102 
106  Jossef  103 
107  Dylan  103 
108  Diane  105 
109  Gigi   105 
110  Michael  106 

我需要得到「106約瑟夫」的所有管理人員的例子,其結果必然是:

106  Josef  103 
103  Roberto  101 
101  Ken   NULL 

什麼是最好的SQL服務器查詢做到這一點

+0

檢查這個職位。它接近你在找什麼:http://stackoverflow.com/questions/959804/simulation-of-connect-by-prior-of-oracle-in-sql-server – Chandu

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

+1

研究這一個:http://blog.sqlauthority.com/2012/04/24/sql-server-introduction-to-hierarchical-query-using-a-recursive-cte-a-primer/ –

回答

1

你可以做一個while循環去了三個經理,直到你可以得到本金節點,在每次迭代中,代碼將該行插入臨時表中。 這裏是一個例子。

DECLARE @employeeId int 
DECLARE @managerId int 

SET @employeeId=106 
SET @managerId=(SELECT Manager_ID FROM Employees WHERE [email protected]) 

DECLARE @tableEmployee as TABLE 
(
ID int, 
NAME varchar(100), 
MANID INT 
) 
INSERT INTO @tableEmployee SELECT * FROM Employees WHERE [email protected] 

WHILE @managerId is not null 
BEGIN 
INSERT INTO @tableEmployee SELECT * FROM Employees WHERE [email protected] 
SET @managerId=(SELECT Manager_ID FROM Employees WHERE [email protected]) 
END 
SELECT * FROM @tableEmployee 
GO 

我認爲不是最好的,但工程,我希望這有助於:)。

1

我的遞歸CTE的非常生鏽,我沒有一個數據庫方便測試,這將是更容易去另一個方向(經理reportees),但我認爲這將做到這一點,或至少接近:

declare @EmpID int; 
set @EmpId = 106; 

with IDs (ID, Manager_ID) As (
    select ID, Manager_ID FROM Employees WHERE ID = @EmpID 
    UNION ALL 
    SELECT ID, Manager_ID 
    FROM Employees e 
    LEFT JOIN ManagerIDs m on e.ID = m.Manager_ID 
    WHERE e.ID IS NOT NULL 
) 
SELECT e.* 
FROM IDs i 
INNER JOIN Employees e on e.ID = i.ID; 
+0

我試過這個查詢但結果與預期結果不符 –