How to batch modify matching records using mssql database cursors

Source: Internet
Author: User

Requirement: because the project has just been uploaded and there are no votes, in order to show a certain popularity, You need to assign a value to the number of votes for each project at the beginning,

However, each project cannot be the same; otherwise, the problem may be easily identified.
Copy codeThe Code is as follows:
DECLARE @ Id varchar (50)
DECLARE My_Cursor CURSOR -- defines the CURSOR
FOR (SELECT Id FROM dbo. kinpanAwardProject where session = 9) -- locate the desired set and put it in the cursor
OPEN My_Cursor; -- OPEN the 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 data using a random number.
Fetch next from My_Cursor INTO @ Id; -- read the NEXT row of data (put the queried Id in the @ Id variable)
END
CLOSE My_Cursor; -- CLOSE the cursor
DEALLOCATE My_Cursor; -- release the cursor
GO

 

Another method may be better. In my opinion, if you do not need to judge the id, you do not need to query where when modifying the cursor. It is faster to directly modify the current position of the cursor.
Copy codeThe Code is as follows:
DECLARE My_Cursor CURSOR -- defines the CURSOR
FOR (SELECT * FROM dbo. MemberAccount) -- find the desired set and put it in the cursor.
OPEN My_Cursor; -- OPEN the 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 row of data
END
CLOSE My_Cursor; -- CLOSE the cursor
DEALLOCATE My_Cursor; -- release the cursor
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.