废话少说上代码:
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