While 循环函数

While Loop Fuction

我有这个问题

 select         
 Suc,       
 SKU,       
 TipoMov,       
 Prov,      
 sum(Uni) as Uni, sum(Imp_Vta) as Imp_Vta 
 into #Mov 
 from dual where (Mes between 22009 and 22105) 
 and        Suc = 11 
 and        TipoMov in (4,5,8)
 and        Id_Fec_Diaria between '2020-09-28' and '2021-05-17' 
 group by 
 Suc,       SKU,        TipoMov,        Prov

我正在尝试在两个日期之间做一个 while 循环 到目前为止我有这个但是有一个我无法修复或理解的错误。

declare
@FechaMin DATE='2020-09-28',
@FechaMax DATE='2021-05-17';

while (@FechaMin >= @FechaMax)
begin 
        select 
        suc,
        SKU,
        TipoMov,
        Prov,
        sum(Uni) as Uni,
        sum(Imp_Vta) as Imp_Vta
into #Mov
from dual
where (Mes between 22009 and 22105) and
        Suc = 11 and
        TipoMov in (4,5,8) and
        Id_Fec_Diaria >= @FechaMin and Id_Fec_Diaria< @FechaMax
group by 
        suc,
        SKU,
        TipoMov,
        prov) END

感谢您的帮助。

如果我没有弄错你的目的,你必须使用光标来实现你的目标。

您可以用此代码替换您的 while 块:

DECLARE 
    @Suc VARCHAR(MAX), 
    @SKU   VARCHAR(MAX),
    @TipoMov VARCHAR(MAX),
    @Prov VARCHAR(MAX)

DECLARE Mycursor CURSOR
FOR SELECT 
         Suc , 
         SKU ,
         TipoMov,
         Prov 
    FROM 
        dual where (Mes between 22009 and 22105) 
 and        Suc = 11 
 and        TipoMov in (4,5,8)
 and        Id_Fec_Diaria between '2020-09-28' and '2021-05-17'

OPEN Mycursor;

FETCH NEXT FROM Mycursor INTO 
    @Suc , 
    @SKU   ,
    @TipoMov ,
    @Prov ;

WHILE @@FETCH_STATUS = 0
    BEGIN
        -----Your Specific Code
        FETCH NEXT FROM Mycursor INTO 
             @Suc , 
             @SKU   ,
             @TipoMov ,
             @Prov ;
    END;

CLOSE Mycursor;

DEALLOCATE Mycursor;