Sql递归查询,我真的不会呀...

2025-01-21 04:47:13
推荐回答(5个)
回答1:

--测试数据
create table #t
(
[id] int,fid int
)
insert into #t values (1,0)
insert into #t values (2,1)
insert into #t values (3,2)
insert into #t values (4,3)
insert into #t values (6,5)
--查询语句
declare @table table ([id] int,fid int)
declare @id int
declare @row int
set @id = 1 ------输入的id
set @row = 1
while @row >0
begin
insert into @table
select
[id],fid
from
#t
where
fid = @id
set @row =@@rowcount
set select @id=[id] from #t where fid = @id
end

select * from @table

希望能帮到你

回答2:

题目能写直白点吗.......

回答3:

你说的问题很含糊,不怎么明白1

回答4:

有可能实现吗?你这样嵌套下去,总要有个截止的吧?不然会陷入死循环的。。。比如,当id=2时,得到的是

ID FID
1 2

这样,又要重头开始了,永远没完没了。。。或者是我理解错了你的意思?

回答5:

在sql2000下的写法
declare @a int
declare @b int
declare @c int
set @a=1 --初始条件,例如id=1
set @c=1 --计量变量
select @b= fid from table1 where id=@a --中间变量
while @c>0
begin
select * from table1 where id in (select fid from table1 where id=@b)
select @b=id from table1 where id in (select fid from table1 where id=@b)
select @c=count(*) from table1 where id in (select fid from table1 where id=@b)
end
--表table1就是你的表A