2010-10-18 13 views
1

Je suis en train de créer une requête sur une table très simple (organisations)CTE récursives - un nombre limité de lignes

j'ai les colonnes

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 

....

Parce que de niveau différent, je ne sais pas comment créer une requête, qui me délivre toutes les organisations supérieures, à partir d'un niveau spécifique

J'ai essayé ce code

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 

Mais avec cette requête, je reçois tout et je ne sais pas, comment je peux interroger seulement les organisations supérieures, par exemple. pour le site de production 1 Maintenance. (peut être 1 ou jusqu'à 5)

Une manière pourrait être une jointure sur la table mais je pense, c'est loin d'être performant.

J'ai vu des requêtes CTE récursives, mais je ne suis pas familier. Alors apprécie l'aide.

Répondre

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

C'est génial et tellement rapide! J'ai testé et ça marche vraiment. Merci 1000 fois Martin – Bastian

Questions connexes