alter proc proc_cte
@uid int
as
;with cte(UID,UName,[Level],FromId)
as(
select UID,UName,0 as [Level],FromId from Info where UID=@uid
union all
select a.UID,a.UName,b.Level+1 [Level],a.FromId from cte as b join Info a on a.uid=b.FromId
)
select * from cte --option(MAXRECURSION 5)
exec proc_cte 8
select * from dbo.Info
1 0 一级用户1
2 0 一级用户2
3 1 用户1-1
4 1 用户1-2
5 3 用户1-1-1
6 5 用户1-1-1-1
7 6 用户1-1-1-1-1
8 7 用户1-1-1-1-1-1
8 用户1-1-1-1-1-10 7
7 用户1-1-1-1-1 1 6
6 用户1-1-1-1 2 5
5 用户1-1-1 3 3
3 用户1-1 4 1
1 一级用户1 5 0
Merge Into t_A As a
Using t_B as b on a.id=b.id
When Matched then
update set a.SNO=b.SNO
When Not Matched then
Insert(id,SNO) values(b.id,b.SNO);