用sql的Function实现递归树

用sql的方法实现递归树 -----MS SQL Server中

tb_city表结构如下
id      name      parentid
1      湖北      0
2      湖南      0
3      武汉      1
4      仙桃      1
5      长沙      2
6      蔡甸      3

定义函数

create function c_tree(@initid int)/*定义函数c_tree,输入参数为初始节点id*/
returns @t table(id int,name varchar(100),parentid int,lev int)/*定义表t用来存放取出的数据*/
begin 
  declare @i int/*标志递归级别*/
  set @i=1
  insert @t select id,name,parentid,@i from tb_city where id=@initid
  while @@rowcount<>0
  begin
  set @i=@i+1
  insert @t select a.id,a.name,a.parentid,@i from tb_city as a,@t as b
 where b.id=a.parentid and b.lev=@i-1
  end
return
end

 

 

执行
使用函数
select * from c_tree(1) /*取湖北下面的子节点*/

 

Oracle中的实现
select *  from TB_CITY
/*此处可写WHERE语句限制*/
start with ID=1
connect by prior ID=PARENTID

你可能感兴趣的:(oracle,sql,C++,c,SQL Server)