34,576
社区成员
发帖
与我相关
我的任务
分享
-- > 测试数据: @T
declare @T table (id int,up int)
insert into @T
select 2,1 union all
select 3,1 union all
select 4,1 union all
select 5,2 union all
select 6,2 union all
select 7,5 union all
select 8,5 union all
select 9,7
declare @id int
set @id = 9
while @@rowcount > 0 select @id = up from @T where id = @id and up <> 1
select @id
create function F_test(@ID int)
returns int
as
begin
declare @UPID int
select @UPID=up from T where ID=@ID
if coalesce(@UPID,1)<>1
return dbo.F_test(@UPID)
return @ID
end
select dbo.F_test(9)
create table T(ID int,UP int)
insert T select 2, 1
insert T select 3, 1
insert T select 4, 1
insert T select 5, 2
insert T select 6, 2
insert T select 7, 5
insert T select 8, 5
insert T select 9, 7
declare @ID int
set @ID=9
while exists(select 1 from T where ID=@ID and up<>1 )
select @ID=up from T where ID=@ID and up<>1
select @ID