首页 > 其他 > 详细

简单自关联表中,查找所有下级数据的函数

时间:2015-12-14 16:39:10      阅读:362      评论:0      收藏:0      [点我收藏+]
if exists (select * from sys.objects where name=func_all_related_levels)
    drop function func_all_related_levels
go
create function func_all_related_levels (
    @id int
)
returns @result table (
    id int
)
as
begin
    ------第一次插入数据。
    declare @total int;
    select @total = count(*) from TestTable where PId = @id
    if @total = 0
        return;
    insert @result
        select Id from TestTable where PId = @id;
    ------遍历,可用。
    declare @cursor int = 0;
    while @cursor < @total
        begin
            declare @nextId int;
            select @nextId = id from @result order by id offset (@cursor) rows fetch next 1 rows only;
            insert @result
                select id from dbo.func_all_related_levels(@nextId);
            set @cursor = @cursor + 1;
        end

    ------游标,出现多余数据。
    --declare c cursor for select id from @result;
    --open c;
    --while @@FETCH_STATUS = 0
    --    begin
    --        declare @nextId int;
    --        fetch next from c into @nextId;
    --        insert @result
    --            select id from dbo.func_all_related_levels(@nextId);
    --    end
    --close c;
    --deallocate c;
    return;
end

 

简单自关联表中,查找所有下级数据的函数

原文:http://www.cnblogs.com/ly45/p/5029482.html

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