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

Rapporto del responsabile dei dipendenti - SQL Server

Declare @t table(empid int, empname varchar(20), managerID int)

insert into @t 
select 1,'A',null union all
select 2,'B',1 union all
select 3,'C',1 union all 
select 4,'D',2

;with CTE AS
(
    Select empid,empname,managerID,
    Cast(empname As Varchar(max)) As ReportingManager
    from @T
    where managerID is null

    UNION ALL

    Select T.empid,T.empname,T.managerID,
    Cast(CTE.empname+'->'+t.empname As Varchar(max)) As ReportingManager
    from @T As T
    INNER JOIN CTE ON T.managerID=CTE.empid 
)
SELECT *
FROM CTE