SQL SERVER 2008递归

tab1 表结构:

create tab1 (

id int primary key identity(1,1),

parentid int not null,

name varchar(25)

)

递归语法(利用CTE表达式):

1.根据父id递归查询子id

with tem1(id,parentid,name) as(

  select id,parentid,name from tab1 where id = 1

  union all

  select tab1.id,tab1.parentid,tab1.name from tab1,tem1

  where tab1.parentid = tem1.id

)

select * from tem1

2.根据子id递归查询父id

with tem1(id,parentid,name) as(

  select id,parentid,name from tab1 where id = 1

  union all

  select tab1.id,tab1.parentid,tab1.name from tab1,tem1

  where tab1.id= tem1.parentid

)

select * from tem1

 

posted @ 2013-07-29 19:47  andysd  阅读(423)  评论(0编辑  收藏  举报