动态递归SQL查询(查询第一层下面所有的分支)
发布网友
发布时间:2022-04-08 05:47
我来回答
共1个回答
热心网友
时间:2022-04-08 07:16
-- for M$SQL 2000+
declare @result table (id int, pid int, idpath varchar(512))
insert into @result
select id,pid, cast(id as varchar)
from thetable
where id = @id
while @@rowcounts > 0 begin
insert into @result
selectt a.id, a.pid, b.idpath+'/'+cast(a.id as varchar)
from thetable a
join @result b on b.id = a.pid
where 1=1
and not exists (select 1
from @result c
where a.id = c.id)
end
说明:
id: 各个元素的ID, pid: 元素的上级ID