Once, the SQL in the loop processing the current row of data and the previous row of data wasted a lot of my time, learned to find it so easy, in fact, learning is so, difficult people will not be difficult.
In the following cases, it is simpler to use the cursor to loop through the data in the table #temptable and then add the argument1 from the current row and the previous row to the argument2 of the current row.
--drop table #temptableCreate Table#temptable (argument1int, Argument2int, Argument3datetime)Declare @rowcount int,@argument1 int,@argument2 nvarchar( -),@argument3 datetimeSet @rowcount=1Set @argument1=1Set @argument2=0Set @argument3=GETDATE() while(@rowcount< -)begin Insert into#temptable (ARGUMENT1,ARGUMENT2,ARGUMENT3)Values(@argument1,@argument2,@argument3) Set @argument1=@argument1 + DatePart( Day,@argument3) Set @argument3=@argument3-1 Set @rowcount = @rowcount + 1End--SELECT * from #temptableDeclare @lastargument2 intSet @lastargument2=0Set @argument2=0Declare_cursor cursor for(SelectArgument1 from#temptable)Open_cursor;Fetch Next from_cursor into @argument2 while @ @fetch_status = 0begin Update#temptableSetArgument2=@argument2+@lastargument2 where Current of_cursor Set @lastargument2=@argument2 Fetch Next from_cursor into @argument2 EndClose_cursordeallocate_cursor--SELECT * from #temptable
Ask a question:
The first fetch next from the _cursor into @argument2 why not put in the first row of the while loop and delete the second row? I remember that I was wrong here, hehe.