在存储过程中,我有2个while循环,我需要避免这些循环并使用游标或递归cte
create procedure Parent_Child_UserDetails_Schedule
as
begin
Set nocount on
create table #temptab(id int, userid int, parentid int)
select userid, 1 as valid
into #users
from userdetails
where isactive = 1
truncate table Parent_Child_UserDetails
while(select count(*) from #users where valid = 1) > 0
begin
declare @userid int
select top 1 @userid = userid
from #users
where valid = 1
truncate table #temptab
insert into #temptab(id, userid, parentid)
values(1, @userid, @userid)
declare @id int
set @id = 1
while((select count(*) from userdetails
where parentid in (select userid from #temptab where id=@id ) and isactive = 1) > 0)
begin
insert into #temptab (id, userid, parentid)
select @id + 1, userid, @userid
from userdetails
where parentid in (select userid from #temptab where id = @id)
and isactive = 1
set @id= @id + 1
end
insert into Parent_Child_UserDetails(Parentid, Userid)
select parentid, userid
from #temptab
update #users
set valid = 0
where userid = @userid
end
drop table #temptab
drop table #users
Set nocount off
end
请帮助我.....
答案 0 :(得分:1)
在评论中我们进行对话之后,您需要在Parent_Child_UserDetails
表中插入所有处于活动状态的父ID和用户ID,
您可以用单个insert....select
语句代替代码的RBAR噩梦,如下所示:
insert into Parent_Child_UserDetails(Parentid, Userid)
select parentid, userid
from userdetails as t0
where isactive = 1
and exists
(
select 1
from userdetails as t1
where t1.isavtice = 1
and t1.userId = t0.ParentId
)