sql 循环执行游标

---定义开始和结束时间
declare @st_dt datetime
declare @en_dt datetime
---时间赋值
select @st_dt = '20150601'
select @en_dt = '20150930'
 
---定义中间变量
declare @dt datetime
select @dt = @st_dt
 
---开始按照时间循环执行
while @dt <= @en_dt
begin
    ---这个是个演示,可以替换为需要执行的存储过程
  DECLARE @Tel varchar(50),
        @ID varchar(50)
DECLARE Subscribe_Cursor CURSOR --定义游标
FOR
(
    select top 360 CONVERT(VARCHAR(20),CONVERT(DECIMAL(20,0),F1)),id from SData where Tag=0
)
OPEN Subscribe_Cursor; --打开游标
FETCH NEXT FROM Subscribe_Cursor INTO @Tel,@ID
WHILE @@FETCH_STATUS = 0
    BEGIN
    insert into LS_ReCall(Tel,ReCallPlanDate)values(@Tel,@dt)
    update SData set Tag=1 where id=@ID
     FETCH NEXT FROM Subscribe_Cursor INTO @Tel,@ID; 
    END
CLOSE Subscribe_Cursor; --关闭游标
DEALLOCATE Subscribe_Cursor; --释放游标
    ---中间变量加1
    select @dt = DATEADD(DAY,1,@dt)
    
end



---定义开始和结束时间
declare @st_dt datetime
declare @en_dt datetime
---时间赋值
select @st_dt = '20150602'
select @en_dt = '20150930'
 
---定义中间变量
declare @dt datetime
select @dt = @st_dt
 
---开始按照时间循环执行
while @dt <= @en_dt
begin
      ---定义开始和结束工号
        declare @st_code int
        declare @en_code int
        ---工号赋值
        select @st_code =1
        select @en_code = 18
        ---定义中间变量
        declare @code int
        select @code = @st_code
        while @code <= @en_code
        begin
                DECLARE @ID varchar(50)
        DECLARE Subscribe_Cursor CURSOR --定义游标
        FOR
        (
              select top 20 id from LS_ReCall where ReCallPlanDate=@dt and EmpCode is null
        )
        OPEN Subscribe_Cursor; --打开游标
        FETCH NEXT FROM Subscribe_Cursor INTO @ID
        WHILE @@FETCH_STATUS = 0
            BEGIN
            update LS_ReCall set EmpCode=@code where id=@ID
            FETCH NEXT FROM Subscribe_Cursor INTO @ID; 
            END
        CLOSE Subscribe_Cursor; --关闭游标
        DEALLOCATE Subscribe_Cursor; --释放游标
        ---中间变量加1
       select @code = @code+1
        end
    ---中间变量加1
    select @dt = DATEADD(DAY,1,@dt)
    
end

 

posted on 2015-06-19 14:39  孟德思旧  阅读(653)  评论(0编辑  收藏  举报