sqlserver中递归写法

递归分两种:一种由父项向下级递归,另一种是由子项向上级递归。下面就这两种情况做个简单的处理。

假设有一个表treeview,包含字段 id,parentid,text 分别代表id,上级id,描述字段(这里就不把建表sql写出来了)。

1、由父项递归下级

with cte(id,parentid,text) 
as 
(--父项 
select id,parentid,text from treeview where parentid = 450 --需替换成自己希望查询的id
union all 
--递归结果集中的下级 
select t.id,t.parentid,t.text from treeview as t 
inner join cte as c on t.parentid = c.id 
) 
select id,parentid,text from cte

2、由子级递归父项 

with cte(id,parentid,text) 
as 
(--下级父项 
select id,parentid,text from treeview where id = 450 --需替换成自己希望查询的id
union all 
--递归结果集中的父项 
select t.id,t.parentid,t.text from treeview as t 
inner join cte as c on t.id = c.parentid 
) 
select id,parentid,text from cte

 简单的例子。 

  

原文地址:https://www.cnblogs.com/iceriver315/p/9704800.html