SQL circularly processes the addition and subtraction of the current row data and the previous row data


In the following example, it is relatively simple to use the cursor to cycle the data in the table #temptable, and then add argument1 in the current row and the previous row and store it in argument2 in the current row.

--drop table #temptable
create table #temptable
  argument1 int,
  argument2 int,
  argument3 datetime

declare @rowcount int,@argument1 int,@argument2 nvarchar(50),@argument3 datetime
set @rowcount=1
set @argument1=1
set @argument2=0
set @argument3=GETDATE()

  insert into #temptable(argument1,argument2,argument3)
  set @[email protected] + datepart(day,@argument3)
  set @[email protected]  
  set @rowcount = @rowcount + 1

--select * from #temptable

declare @lastargument2 int
set @lastargument2=0
set @argument2=0
declare _cursor cursor for(select argument1 from #temptable)
open _cursor;
fetch next from _cursor into @argument2 
while @@fetch_status = 0
  update #temptable
  set [email protected][email protected]
  where current of _cursor
  set @[email protected]  
  fetch next from _cursor into @argument2 
close _cursor
deallocate _cursor

--select * from #temptable

Ask a question:

First sentence fetch next from_ Why can’t the sentence “cursor into @ argument2” be placed in the first line of the while loop and delete the second line? I remember I made a mistake here, ha ha.