sql递归函数示例

发布时间:2020-03-06编辑:脚本学堂
分享一例sql递归函数的代码,学习sql递归查询的朋友可以参考下。

例子,sql递归函数
 

复制代码 代码示例:

create table t_tree(id int IDENTITY(1,1) ,parentid int,name varchar(10))
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递归查询的几种实现方法
sql函数实现递归查询示例
sql递归查询代码(cte应用)
sql2005递归查询的例子
sql递归查询(with cte实现)
sql 递归查询的代码(图文)