首页 > 数据库技术 > 详细

sql递归函数(自定义函数递归查找) 能返回递归的层次

时间:2014-03-15 02:25:16      阅读:659      评论:0      收藏:0      [点我收藏+]

实现效果图如下:

bubuko.com,布布扣

 

创建表:

create table t_tree

(

    id int IDENTITY(1,1),

    parentid int,

    name varchar(10)

)

go

 

插入测试数据:

insert into t_tree select 0,‘‘
insert into t_tree select 1,‘‘
insert into t_tree select 1,‘‘
insert into t_tree select 2,‘‘
insert into t_tree select 3,‘‘
insert into t_tree select 3,‘‘
insert into t_tree select 5,‘‘
insert into t_tree select 5,‘‘
insert into t_tree select 5,‘‘
go

 

创建函数:

create function get_child(@id int)
     returns @child table (id int,parentid int,name varchar(10),level int)
as
     begin
          declare @level int
          set @level=0
          insert into @child  select *,@level from t_tree where id=@id
          while @@rowcount>0
          begin
              set @level=@level+1
              insert into @child  select a.*,@level from t_tree a,@child b  where b.id=a.parentid and b.level=@level-1
          end
          return
     end
go

 

执行:

    select * from get_child(1)

sql递归函数(自定义函数递归查找) 能返回递归的层次,布布扣,bubuko.com

sql递归函数(自定义函数递归查找) 能返回递归的层次

原文:http://www.cnblogs.com/lyuec/p/3601347.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!