在数据库设计的时候,经常会遇到树形表结构,如何根据一个节点Id,获取所有子节点的Id列表呢,这需要用到递归,递归函数如下:

比如说表Table中主机为Id,通过fatherId关联子节点的。

Create function [dbo].[getchildrenId](@id varchar(50))

returns varchar(max)

begin

declare @ids varchar(max);

set @ids='';

select @ids =isnull(@ids +',','') +tbchild.Id from table tbfather

inner join table tbchild on tbchild.fatherId=tbfathe.Id

where tbfather.Id in (select col from dbo.f_split(@id,',')))

if(exists(select tbchild.Id from table tbfather

inner join table tbchild on tbchild.fatherId=tbfathe.Id

where  tbfather.Id in (select col from dbo.f_split(@id,','))))

begin

  set @ids=@ids+[dbo].getchildrenId(@ids)----开始递归调用

end

return @ids;

end

其中dbo.f_split是一个分割字符串的函数,定义如下:

createfunction f_splitstr(@SourceSql varchar(8000),@StrSeprate varchar(100))

  • returns @temptable(F1 varchar(100))
  • as
  • begin
  • declare @ch asvarchar(100)
  • set @SourceSql=@SourceSql+@StrSeprate
  • while(@SourceSql<>'')
  • begin
  • set @ch=left(@SourceSql,charindex(',',@SourceSql,1)-1)
  • insert @tempvalues(@ch)
  • set @SourceSql=stuff(@SourceSql,1,charindex(',',@SourceSql,1),'')
  • end
  • return
  • end

好了,结束。

 

 

posted on 2013-06-05 19:02  Kelly_HanShuai  阅读(518)  评论(0)    收藏  举报