Popular Posts

Monday, April 25, 2011

Recursive Store Procedure


create proc [dbo].[dba_1]
@agentcode varchar(20),
@level int,
@parentagent varchar(20),
@fromdate datetime,
@uptodate datetime
as
set nocount on
DECLARE @custtable TABLE
( Custcode varchar(20))

DECLARE @agenttable TABLE
( id int identity(1,1),agentcode varchar(20),parentagent_t varchar(20) )

insert into @custtable select na from cust where acode=@agentcode

declare @amt numeric(18,3),@ID  int,@agent_code_local varchar(20)

select @amt=sum(instlamt) from gstockch where na=@agentcode and childna in (selecT * from @custtable)
and dt between @fromdate and @uptodate insert into dba_table
select @agentcode,@amt,@level,@parentagent

set @level=@level+1

insert into @agenttable select na,@agentcode from agent where imme=@agentcode

declare @intloop int,@intuptoloop int,@parentagentttt varchar(20)
set @intloop=1
set @intuptoloop=(SELECT count(1) FROM @agenttable)
while @intloop<=@intuptoloop
begin
    select @agent_code_local=agentcode,@parentagentttt=parentagent_t from @agenttable where id=@intloop
    EXEC dba_1 @agent_code_local,@level,@parentagentttt,@fromdate,@uptodate
    set @intloop=@intloop+1
end



No comments:

Post a Comment