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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-05
  • 2021-06-07
猜你喜欢
  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
  • 2018-12-23
  • 2021-07-09
  • 2022-01-19
  • 2021-10-26
相关资源
相似解决方案