--递归
create table Dept(
DepartNO varchar(10),
DepartName varchar(20),
TopNo varchar(10))
delete from dept
insert into Dept values('001','董事会','0')
insert into Dept values('002','总裁办公室','001')
insert into Dept values('003','财务部','001')
insert into Dept values('004','市场部','002')
insert into Dept values('005','公关部','002')
insert into Dept values('006','销售部','002')
insert into Dept values('007','分销处','006')
insert into Dept values('008','业务拓展处','004')
insert into Dept values('009','销售科','007')
go
select *
from dept
go
with Dept_CTE as
(
select DepartNO,
DepartName,
TopNo from Dept
where DepartNo='002'
union all
select child.DepartNO,
child.DepartName,
child.TopNo from Dept_CTE as Parent
join Dept as child
on parent.DepartNO=child.TopNo
)
select * from Dept_CTE