>DECLARE @nBalancepre int, @nRecNum int, @nBalancepost int, @nYear int, @nRun int, @nItem int >SET @nYear=2019 >SET @nRun=1 >SET @nItem=100 >--get the first balancepre to start calculation, you must adapt this to dinamically change item and year, I assume that run is always 1 to start >SET @nBalancepre=(SELECT TOP 1 Balancepre from balances where item=@nItem and year=@nYear and run=@nRun) >--prepare the cycle >SELECT null kctrl, item, year, run, amount, ROW_NUMBER() OVER(ORDER BY item,year,run) as recnum into #selrows FROM balances where item=@nItem and year=@nYear and run=@nRun; >WHILE (SELECT count(*) FROM #selrows WHERE isnull(kctrl, 0) = 0) > 0 >BEGIN > --record to iterate > SET @nRecNum=(SELECT MIN(recnum) FROM #selrows WHERE ISNULL(kctrl, 0) = 0) > --get balancepost calculated from current row > SELECT @nBalancepost=@nBalancepre+amount, @nYear=year, @nRun=run from #selrows where recnum=@nRecNum > --start the update > UPDATE balances set balancepre=@nBalancepre, balancepost=@nBalancepost where item=@nItem and year=@nYear and run=@nRun > --prepare balancepre for next row > SET @nBalancepre=@nBalancepost > --update cycle to continue with next > UPDATE #selrows set kctrl=1 where recnum=@nRecNum >END >--at this moment all the records must be update accordingly >>