MySQL non-source code learning: two easy-to-ignore vertices in the Stored Procedure

Source: Internet
Author: User

Today, I wrote a slightly more complex stored procedure and shared it with two easy-to-ignore points. If there are packages that happen to encounter the same problem, you can spend less time figuring out the technical content of wood...
 
1. Example of a stored procedure using a cursor
Suppose it is a simple requirement: traverse f from table t, and then search for qualified records in Table t2.
 
Declare stopFlag int;
DECLARE cur_name CURSOR for f from t;
Declare continue handler for not found set stopFlag = 1;
Set stopFlag = 0;
Open cur_name;
REPEAT
FETCH cur_name INTO temp_f;
Begin
Select f3 into my_result from t2 where f2 = temp_f limit 1;
End;
UNTIL stopFlag = 1
End repeat;
CLOSE cur_name;
 
2. Point 1
Suppose that the t table has n records. How many cycles does this loop have?
Actually n + 1 times. Because stopFlag is 1 when the last line of t is reached. This value is modified in the next fetch, but after the modification, it enters the begin and no further judgment. Therefore, it will be executed once more. The value of temp_f is the same as that of the previous one.
 
Solution: After Entering Begin, judge the stopFlag value.
 
3. Point 2
Sometimes you may find that you exit after n cycles. Why?
The reason is that if select f3 into my_result from t2 where f2 = temp_f limit 1; the condition cannot match the row, set stopFlag = 1 will be triggered when you try to assign values to my_result; as a result, the exit condition is met after the until judgment.
 
Solution: pay special attention to the statements that appear inside the loop body. If so, save the stopFlag to a temporary variable after entering begin, and grant the Temporary Variable back before.

Author: "follow-up knife Ding Qi"
 

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.