Declare @LastAmt money
Declare @Date datetime
Declare @Document_Date docdate
Declare @GRN money
Declare @DN money
Declare @Balance money
Declare @Present_Amt money
Set @Date = '2014-10-01'
Select @LastAmt = Sum(Amt) From TableName where Data < @Date
Declare Cur_1 Cursor For
Select Document_Date, GRN, DN, Balance
From TableName
Where Date Between '2014-10-01' And '2014-10-30'
Order By Document_Date ASC
Set @Present_Amt = @LastAmt
Open Cur_1
Fetch Next From Cur_1 Into @Document_Date, @GRN, @DN, @Balance
WHILE (@@Fetch_Status =0)
Begin
Select * INTO #TempTable
From (Select @Document_Date as Date, @GRN as GRN, @DN as DN
, @Present_Amt + (@GRN-@DN) as NewBalance
)GRNTable
Set @Present_Amt = @Present_Amt + (@GRN-@DN)
Fetch Next From Cur_1 Into @Document_Date, @GRN, @DN, @Balance
End
Close Cur_1
Deallocate Cur_1
Select * from #TempTable
Drop Table #TempTable