1、数据准备
假定有一个表DiGui,有两个字段Id int ParentId int
Id ParentId
4 0
5 0
7 0
2 1
8 5
15 5
9 7
14 11
30 15
23 15
41 18
104 23
42 30
39 30
53 39
67 39
88 39
107 39
2、目的:通过传入ParentId(=5),返回该记录的所有递归数据,即
Id ParentId
8 5
15 5
30 15
23 15
42 30
39 30
53 39
67 39
88 39
107 39
3、Sql语句实现
with temp ( [Id], [parentid])
as
(
select Id, parentid
from DiGui
where [parentid] = 15
union all
select a.Id, a.parentid
from DiGui a
inner join temp on a.[parentid] = temp.[Id]
)
select * from temp