Solve the classic 1+2+...+100 problem with SQL cursors!

Source: Internet
Author: User

I've never been in touch with SQL cursors before, and for the first time today, I think of the classic 1+2+...+100 in programming languages.

The environment is SqlServer2008.

To build a table statement:

CREATE TABLE [dbo]. [Tcursor] (
[ID] [int] not NULL,
[Sum] [INT] Null
) on [PRIMARY]

The fill ID is then 1~100,sum to 0.

DECLARE @i int
Set @i=1
while (@i <=100)
Begin
Insert into Tcursor (Id,[sum]) VALUES (@i,0)
Set @[email protected]+1
End

The following statement is then used to implement the summation:

DECLARE cur cursor forward_only local for
Select ID from Tcursor

Open cur

DECLARE @i int
Set @i =1
DECLARE @lastsum int
Set @lastsum =0

While @i<100
Begin
FETCH NEXT from cur to @i
Set @lastsum [email protected][email protected]
Update tcursor set [Sum] = @lastsum where ID = @i
End

Close cur

The final effect is as follows:

The importance of this sense of the cursor, but also feel that the problem is very representative, hope to learn the cursor of the Novice also have a role.

Also ask Daniel to point out the deficiencies, or give a better algorithm.

Solve the classic 1+2+...+100 problem with SQL cursors!

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.