递归 子项查父项

来源:互联网 发布:电磁辐射测试软件 编辑:程序博客网 时间:2024/06/14 05:02


树形结构示例













create function fnGetFather(@id nvarchar(30))

returns @t table(zth nvarchar(30),fth nvarchar(30))
as
begin
    select @id = fth from gx where zth = @id
    while @@rowcount > 0
    begin
        insert into @t select zth,fth from gx where zth = @id
        select @id = fth from gx where zth = @id
    end
return 
end

GO


select * from dbo.fnGetFather('1') order by 1 DESC

通过执行函数,我想要这样的结果

(5、8)

(5、9)

(6、10)

(7、11)


但每次执行函数,返回的值都不一样,有如下规律。

执行第一次

(5、8)

(5、9)        

 

执行第二次

(6、10)      

执行第三次(7、11)


请大家帮忙改改以上函数,多谢了!!   qq: 636297788

原创粉丝点击