반응형
재귀적 CTE 예
--A simple self join
Select Employee.Name as [Employee Name],
IsNUll(Manager.Name, 'Super Boss') as [Manager Name]
from tblEmployee Employee
left join tblEmployee Manager
on Employee.ManagerId = Manager.EmployeeId
With
EmployeesCTE (EmployeeId, Name, ManagerId, [Level])
as
(
Select EmployeedId, Name, ManagerId, 1
from tblEmployee
where ManagerId is null
union all
Select tblEmployee.EmployeedId, tblEmployee.Name,
tblEmployee.ManagerId, EmployeesCTE.[Level] + 1
from tblEmployee
join EmployeesCTE
on tblEmployee.ManagerID = EmployeesCTE.EmployeeId
)
Select EmpCTE.Name as Employee, Isnull(MgrCTE.Name, 'Super Boss') as Manager, EmpCTE.[Level]
from EmployeesCTE EmpCTE
left join EmployeesCTE MgrCTE
on EmpCTE.ManagerId = MgrCTE.EmployeeId
계속 스스로를 참조하는 재귀형 CTE
반응형
'Database > SQL Server' 카테고리의 다른 글
SQL Server - 정규화, 1~3 정규형 [1NF, 2NF, 3NF] (0) | 2020.12.08 |
---|---|
SQL Server - 데이터베이스 정규화 Database normalization (0) | 2020.12.08 |
SQL Server - 수정가능한 공통 테이블 식(Updateable Common Table Expression) (0) | 2020.12.08 |
MS SQL-파생 테이블 정리 & 공통 테이블 식(CTE) in SQL Server (0) | 2020.12.08 |
SQL Server - 트리거, DML(Data Manipulation Language) trigger에 대해 (0) | 2020.12.05 |