WITH cte AS
(
SELECT Id,Pid,DeptName,0 AS lvl FROM Department
WHERE Id = 2
UNION all
SELECT d.Id,d.Pid,d.DeptName,lvl+1 FROM cte c inner join Department d
ON c.Pid = d.Id
)
SELECT * FROM cte
WITH cte AS
(
SELECT Id,Pid,DeptName,0 AS lvl FROM Department
WHERE Id = 2
UNION all
SELECT d.Id,d.Pid,d.DeptName,lvl+1 FROM cte c inner join Department d
ON c.Pid = d.Id
)
SELECT * FROM cte