WITH DepartmentTree AS (
SELECT
Id,
Code,
Name,
UpDepartmentId,
1 as Level
FROM
SaintEir_Department
WHERE Id = 1
UNION ALL
SELECT
e.Id,
e.Code,
e.Name,
e.UpDepartmentId,
o.Level + 1 as Level
FROM
SaintEir_Department e
INNER JOIN DepartmentTree o
ON o.Id = e.UpDepartmentId
)
SELECT * FROM DepartmentTree;