WHILE @Suma < @ZalihaVP
begin
Insert into @Promet (Kljuc, Kolicina, Datum, StarostPrometa)
select top 1 m.acKey, anQTY, m.adDate, DATEDIFF(d, m.adDate, getdate())
from tHE_Move m inner join tHE_MoveItem mi
on m.acKey = mi.acKey
where acReceiverStock = 'Y'
and acReceiver = @Skladiste
and acIdent = @Ident
and m.acKey not in(select Kljuc from @Promet)
order by adDate desc
set @Suma = @Suma + (select SUM(kolicina) from @Promet)
if @Suma > @ZalihaVP begin update @Promet set Kolicina = Kolicina - (@Suma - @ZalihaVP) where KLjuc = (select top 1 KLjuc from @Promet order by Datum) end
if @Suma > @ZalihaVP begin set @Suma = @ZalihaVP end
end
This is my WHILE loop, I have problem here. @ZalihaVP = 92 @Suma = 0
Records of @promet.kolicina are: 40, 50, 50
On third record, @Suma it's greather than @ZalihaVP 40 + 50 + 50 = 140 > @Suma and third record it's not inserted, but I want them to insert.
How I can send @Suma < @Zaliha on the end after insert?