Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Query dell'albero di 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 a marc_s