Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Ordenação de Menu Recursivo SQL


Ok, entendi :) -- Isso parece funcionar aqui.
DECLARE @Categories TABLE (
 ID int PRIMARY KEY
,Title varchar(256)
,ParentID int
)

INSERT INTO @Categories
VALUES
 (1, 'All', 0)
,(2,'Banking', 8)
,(3,'USAA Checking', 2)
,(4,'USAA Mastercard', 2)
,(5,'Medical', 8)
,(6,'Jobs', 8)
,(7,'Archive', 1)
,(8,'Active', 1)
,(9,'BoA Amex', 2)


;
WITH  CategoryTree
        AS (SELECT  r.ID, r.Title, 0 Level, r.ParentID,
                    CAST(r.Title AS VARCHAR(1000)) AS "Path"
            FROM    @Categories r
            WHERE   r.ParentID = 0
            UNION ALL
            SELECT  c.ID, c.Title, p.Level + 1 AS Level, c.ParentID,
                    CAST((p.path + '/' + c.Title) AS VARCHAR(1000)) AS "Path"
            FROM    @Categories c
                    INNER JOIN CategoryTree p
                      ON p.ID = c.ParentID
           )
  SELECT  ID, REPLICATE('-----', Level) + Title AS Title, [Path]
  FROM    CategoryTree
  ORDER BY [Path]