Sorry couldn't think up a simple scenario that made sense to do in a loop so I will just do an example without worrying about making sense
we have this table called tblStock with the fields
Sun,Mon,Tue,Wed,Thu,Fri
and on sunday there is a certain amount of stock recorded. At the end of each day the amount that has been added and removed is recorded in another table called tblTodaysMovement. After the movements have been recorded the exampl loop is run to update the stock
-
Declare @Day int,@Added int,@Removed int, @Stock int
-
set @Day=1
-
while @Day<5
-
begin
-
set @Added=(Select Added from tblTodaysMovement)
-
set @Removed=(Select Removed from tblTodaysMovement)
-
set @Stock=(Select case when @Day=1 then Sun else 0 end +
-
case when @Day=2 then Mon else 0 end +
-
case when @Day=3 then Tue else 0 end +
-
case when @Day=4 then Wed else 0 end +
-
case when @Day=5 then Thu else 0 end
-
-
if @Day=1 begin update tblstock set Mon=@Stock+@Added-@Removed end
-
if @Day=2 begin update tblstock set Tue=@Stock+@Added-@Removed end
-
if @Day=3 begin update tblstock set Wed=@Stock+@Added-@Removed end
-
if @Day=4 begin update tblstock set Thu=@Stock+@Added-@Removed end
-
if @Day=5 begin update tblstock set Fri=@Stock+@Added-@Removed end
-
set @Date=@Date+1
-
end
-
As I said, this is not a good example scenario and there is no way I would do it like this. It is just an example of one way of looping a query and adjusting it according to parameters that change on each loop. I have better examples but they are too long and complex to explain here.
I hope you find this helpful in getting you started