2010-10-18 70 views
1

我想在一個非常簡單的表創建一個查詢(組織)遞歸CTE - 行的數量有限

我列

Organisation, Manager, Superior_Organisation 
CEO 
Leadership Team, David, CEO 
Production Management, Alex, Leadership Team 
Production Site 1, Francoise, Production Management 
Production Site 2, Steve, Production Management 
Production Site 1 Maintenance, Alan, Production Site 1 

....

因爲不同級別的人,我不知道如何創建一個查詢,這爲我提供所有上級組織,從一個特定級別開始

我試過這個代碼

declare @i int 
select @i = 0 
-- keep going until no more rows added 
while @@rowcount > 0 
begin 
select @i = @i + 1 
-- Get all children of previous level 
SELECT  organisations.Organisation, organisations.Manager, 
organisations.Superior_Organisation 
FROM   organisations 
end 

但是,使用此查詢,我得到所有,我不知道,我怎麼只能查詢優等組織,例如,用於生產現場1維護。 (可以是1或最多5)

一種方法可能是在桌面上的連接,但我認爲,這遠離高性能。

我見過一些遞歸的CTE查詢,但我不熟悉。所以感謝幫助。

回答

2
;WITH organisations AS 
(
SELECT 'CEO' AS Organisation, cast(NULL as varchar(50)) AS Manager, cast(NULL as varchar(50)) AS Superior_Organisation UNION ALL 
SELECT 'Leadership Team', 'David', 'CEO' UNION ALL 
SELECT 'Production Management', 'Alex', 'Leadership Team' UNION ALL 
SELECT 'Production Site 1', 'Francoise', 'Production Management' UNION ALL 
SELECT 'Production Site 2', 'Steve', 'Production Management' UNION ALL 
SELECT 'Production Site 1 Maintenance', 'Alan', 'Production Site 1' 
), 
cte As (
SELECT Organisation, Manager, Superior_Organisation 
FROM   organisations 
WHERE organisations.Organisation = 'Production Site 1 Maintenance' 
UNION ALL 
SELECT o.Organisation, o.Manager, o.Superior_Organisation 
FROM   organisations o 
JOIN cte ON cte.Superior_Organisation = o.Organisation 
) 
SELECT Organisation, Manager, Superior_Organisation 
FROM cte 
WHERE Organisation <> 'Production Site 1 Maintenance' 
+0

這太棒了,太快了!我測試過,它真的很有用。感謝馬丁1000倍 – Bastian 2010-10-18 15:03:34