1

J'ai une table nommée Department avec 3 colonnes: DepartmentID, DepartmentName, ParentID.ORDER BY hiérarchie enfant-parent utilisant la procédure stockée MS SQL Server

Voir SQL Fiddle pour plus de détails

Je veux commander les résultats par ParentID et génération. Comme ceci:
╔═════════╦════════════════╦════════════╦════ ══════╗
║ ChildID ║ DepartmentName ║ Génération ║ ParentID ║
╠═════════╬════════════════╬══ ══════════╬══════════╣
║ 1 ║ Gestionnaire ║ 0 ║ NULL ║
║ 6 ║ Ventes ║ 1 ║ 1 ║
║ 7 ║ Flotte ║ 1 ║ 1 ║
║ 4 ║ Chargement ║ 2 ║ 7 ║
║ 5 ║ Transport ║ 2 ║ 7 ║
║ 2 ║ IT ║ 2 ║ 6 ║
║ 3 ║ ║ alimentaire 2 ║ 6 ║
╚═════════╩═════ ═══════════╩════════════╩══════════╝

J'ai essayé différents ORDER BY s mais aucun travaillé.

Ma procédure stockée:

WITH Hierarchy(ChildId, DeparmentName, Generation, ParentID) 
AS 
(
SELECT DepartmentID, DeparmentName, 0, ParentID 
    FROM Departments AS FirtGeneration 
    WHERE ParentID IS NULL 
UNION ALL 
    SELECT NextGeneration.DepartmentID, NextGeneration.DeparmentName, Parent.Generation + 1, Parent.ChildId 
     FROM Departments AS NextGeneration 
     INNER JOIN Hierarchy AS Parent ON NextGeneration.ParentID = Parent.ChildId  
) 
SELECT * FROM Hierarchy 
OPTION(MAXRECURSION 32767) 

J'utilise MS SQL Server 2005

Répondre

1

Essayez stocker le chemin vers le haut dans la requête hiérarchique:

WITH Hierarchy(ChildId, DeparmentName, Generation, ParentID, Path) AS (
     SELECT DepartmentID, DepartmentName, 0, ParentID, 
      RIGHT('000' + CAST(DepartmentID as VARCHAR(MAX)), 3) as Path 
     FROM Departments FirstGeneration 
     WHERE ParentID IS NULL 
     UNION ALL 
     SELECT NextGeneration.DepartmentID, NextGeneration.DeparmentName, Parent.Generation + 1, Parent.ChildId, 
      Path + '-->' + CAST(RIGHT('000' + CAST(NextGeneration.DepartmentID as VARCHAR(MAX)), 3) 
     FROM Departments NextGeneration INNER JOIN 
      Hierarchy Parent 
      ON NextGeneration.ParentID = Parent.ChildId  
    ) 
SELECT h.* 
FROM Hierarchy h 
ORDER BY path 
OPTION(MAXRECURSION 32767); 
+0

Le code ne courir. Il y a quelques erreurs de syntaxe SQL. – milo2011