MSSQL Database Cursors Batch modification of eligible records method _mssql2005

Source: Internet
Author: User
Tags mssql first row
Requirements: Because the project just uploaded, no votes, in order to show a certain popularity, the need to be in the beginning of the number of votes to assign a value,

But each project can not be the same, otherwise easy to see the problem, hehe.
Copy Code code as follows:

DECLARE @Id varchar (50)
DECLARE my_cursor Cursor--Defining cursors
For (SELECT Id from Dbo.kinpanawardproject where session=9)--Find the desired collection and place it in cursor
OPEN My_cursor; --Open cursor
FETCH NEXT from My_cursor into @Id; --Read the first row of data (put the ID in the @id variable)
While @ @FETCH_STATUS = 0
BEGIN
PRINT @Id; --Print data (ID)
UPDATE dbo.kinpanawardproject SET proticketcount = CAST (Floor (rand () *30) as int) +40 WHERE Id = @Id; --Update the data using random numbers.
FETCH NEXT from My_cursor into @Id; --Read the next line of data (put the ID of the query into the @id variable)
End
Close my_cursor; --Close cursor
Deallocate my_cursor; --Releasing cursors
Go



There is also a usage that may be better, and I think that if you do not need to judge the ID, you do not need a where query at the time of the modification, and it is faster to modify the cursor's current position directly.
Copy Code code as follows:

DECLARE my_cursor Cursor--Defining cursors
For the SELECT * FROM dbo. Memberaccount)--Find the desired collection and put it in the cursor
OPEN My_cursor; --Open cursor
FETCH NEXT from My_cursor; --Read the first row of data
While @ @FETCH_STATUS = 0
BEGIN
--update dbo. Memberaccount SET UserName = UserName + ' A ' WHERE current of my_cursor; --Update
--delete from dbo. Memberaccount WHERE Current of my_cursor; --Delete
FETCH NEXT from My_cursor; --Read the next line of data
End
Close my_cursor; --Close cursor
Deallocate my_cursor; --Releasing cursors
Go
Related Article

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.