sql2008-cte

if OBJECT_ID('tempdb..#employee') is not null
drop table #employee

create table #employee
(
id int not null,
name varchar(40) null,
fatherid int null
)
insert into #employee values(1001,'a',null)
insert into #employee values(1002,'b',null)
insert into #employee values(1003,'c',1001)
insert into #employee values(1004,'d',1002)
insert into #employee values(1005,'e',1001)
insert into #employee values(1006,'f',1003)
insert into #employee values(1007,'h',1006)
insert into #employee values(1008,'i',1006)
insert into #employee values(1009,'j',1008)
insert into #employee values(1010,'k',1009)
insert into #employee values(1011,'l',1001)
insert into #employee values(1012,'m',1011)

go

with cte1 (id,name,fatherid,lv)
as
(
select ID,name,fatherid,0
from #employee where id = 1001
union all
select e.id,e.name,e.fatherid,cte1.lv+1
from #employee as e inner join cte1
on e.fatherid = cte1.id
)

select * from cte1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值