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!