Practice has proved that the use of cursors in the database is better _ MySQL

Source: Internet
Author: User
Practice has proved that the use of cursors in a database is better. There are two tables in the database, one of which is huge, with about 10 million records (Big) and the other with only 5000 records (small ).

Currently, the table Big needs to be updated based on the table small.

UPDATE Big SET Bf1 = 0 WHERE BigId IN (SELECT BigId FROM Small WHERE Sf1> 0)

However, the execution speed is very slow, and the applications connecting to and using this DB server are also slow and almost unavailable.

Carefully analyze this SQL statement and use IN. Some people say that IN will be split into an OR expression, and the OR statement will not use an index, so sometimes OR will be replaced by union all.

However, union all cannot be used here.

According to the author's conjecture, this SQL statement will probably be searched by the entire table. if there are 10 million records in a large table, it will be at least 10 million times. how can this problem be solved.

So I chose to use a cursor instead. I first extracted the records of the small table and executed them in combination with the large table.


DECLARE curT cursor for select BigId FROM Small WHERE Sf1> 0; DECLARE @ Id INT; OPEN curT; fetch next from curT INTO @ Id; WHILE @ FETCH_STATUS = 0 begin update Big SET Bf1 = 0 WHERE BigId = @ BigId; fetch next from curT INTO @ Id; end close curT; DEALLOCATE curT;

In this way, the maximum number of records in the cursor is 5000, and the BidId has an index in the large table, which is divided into 5000 executions. although it takes some time to compile the connection, however, compared with the massive table-wide search, it is very small.

Practice has proved that the preceding statement is executed in about four minutes, during which the applications using this database are not affected and the speed is also fast.

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.