

--王红波
描述:使用通用表达式实现递归查询
查询id=2的所有子节点
*/
if
exists
(
select
1
from
sys.tables
where
name
=
'
test
'
)
drop
table
test

create
table
test(id
int
,parent_id
int
)
insert
into
test
select
1
,
0
union
all
select
2
,
1
union
all
select
3
,
1
union
all
select
4
,
1

union
all
select
20
,
2
union
all
select
21
,
2

union
all
select
30
,
3
union
all
select
31
,
3
union
all
select
32
,
3

select
*
from
test
;
with
sun(id)
as
(
select
id
from
test
where
id
=
1
--
union
all
select
a.id
from
test a
inner
join
sun b
on
a.parent_id
=
b.id
)

select
*
from
sun
order
by
id

drop
table
test
















































