Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Requête d'arborescence SQL Server

WITH  OrganizationsH (OrgParentFK, OrgPK, OrgName, level, Label) AS
(
    SELECT OrgParentFK, OrgPK, OrgName, 0, CAST(OrgName AS VARCHAR(MAX)) As Label
    FROM Organizations
    WHERE OrgParentFK IS NULL
    UNION ALL
    SELECT o.OrgParentFK, o.OrgPK, o.OrgName, level + 1,  CAST(h.Label + '/' + o.OrgName  VARCHAR(MAX)) As Label
    FROM Organizations o JOIN OrganizationsH h ON o.OrgParentFK = h.OrgPK
)

SELECT OrgParentFK, OrgPK, OrgName, level, Label
FROM OrganizationsH
WHERE OrgPK = 5

h/t en marc_s