SQL loops through the current row in the table data and a value in the previous row +/-

Source: Internet
Author: User
Tags rowcount

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.