SQL 递归查询最顶级目录

废话少说上代码:

create FUNCTION [dbo].[Fun_getParent](@child VARCHAR(30))
returns @t table(vid varchar(100),dt DATETIME) 
as
begin

 INSERT inTO @t  select pid,GETDATE() from 数据库.dbo.testTB where id=@child
    WHILE @@ROWCOUNT<>0
    BEGIN
        INSERT INTO @t SELECT a.pid,GETDATE() FROM 数据库.dbo.testTB AS a 
        INNER JOIN @t AS b ON a.id=b.vid 
        AND NOT EXISTS(SELECT 1 FROM @t WHERE vid=a.pid)
    END
 IF (SELECT COUNT(*)FROM @t)>1
DELETE @t WHERE dt=(SELECT TOP 1 dt FROM @t ORDER BY dt)
RETURN
end

 

转载于:https://www.cnblogs.com/leojon/p/4402315.html

你可能感兴趣的:(SQL 递归查询最顶级目录)