sql递归函数(自定义函数递归查找) 能返回递归的层次
实现效果图如下:
创建表:
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)
欢迎大家踊跃讨论并指出不足或错误的地方,一定及时改进。
联系QQ:106398492
Email:lyuec@sina.com
一份耕耘一份收获,N年工作中经验积累。如需转载请注明出处,多谢合作!
世界没有悲剧和喜剧之分,如果你能从悲剧中走出来,那就是喜剧,如果你沉缅于喜剧之中,那它就是悲剧。