在嵌套的While循环中插入

时间:2017-09-28 10:05:17

标签: sql sql-server sql-server-2008

我试图在嵌套while循环中插入记录.Below是我在SQL server中的存储过程,它只插入两条记录,它应该插入4条记录。这里有什么问题。提前谢谢。

create proc Insert_LeadDistributionClient   
--Insert_LeadDistributionClient   
@LeadDistribution_code varchar(1000) = '100,101'  
,@Client_code varchar(1000) ='1,2'  
,@medium_code varchar(1000) = '10,11'  
as  
begin  
declare @LeadDistributionLength int  
declare @ClientLength int
declare @MediumLength int

declare @SingleLeadDistCode int  
declare @SingleClientCode int  
declare @SingleMediumCode int  

select * into #LeadDistributionCode from dbo.Split(@LeadDistribution_code , ',')  
select * into #ClientCode from dbo.Split(@Client_code , ',')  
select * into #MediumCode from dbo.Split(@medium_code , ',')  

set @LeadDistributionLength = (select count(*) from #LeadDistributionCode)  
set @ClientLength = (select count(*) from #ClientCode)  
set @MediumLength = (select count(*) from #MediumCode)  

while(@ClientLength <> 0 )
begin
  set @SingleClientCode = (select top 1 [data] from #ClientCode)
  while(@LeadDistributionLength <> 0)
  begin
    set @SingleLeadDistCode = (select top 1 [data] from #LeadDistributionCode)
    insert into leaddistributionclient(LeadDistribution_code,Client_code,Medium_Code , LeadRatio_Count , CurrentLead_Count,Is_Sent)  
    select  @SingleLeadDistCode,@SingleClientCode,1 ,0 ,0 ,0  
    delete top (1) from #LeadDistributionCode
    set @LeadDistributionLength = @LeadDistributionLength -1
  end
  delete top (1) from #ClientCode
  set @ClientLength = @ClientLength - 1
end


drop table #LeadDistributionCode  
drop table #ClientCode  
drop table #MediumCode  


end

1 个答案:

答案 0 :(得分:0)

删除此行

delete top (1) from #LeadDistributionCode

开头的第一行添加此行
set @LeadDistributionLength = (select count(*) from #LeadDistributionCode)