How to use MySQL stored procedures and cursor

Source: Internet
Author: User

Example: CopyCode The Code is as follows: Create procedure 'justifygroupnum '()
Not deterministic
SQL Security definer
Comment''
Begin
/* How to Run: Call justifygroupnum ()*/
Declare p_group_id int;
Declare p_num int;
Declare stopflag int;
Declare cursor_name cursor
For select c_group_id, count (*) as num
From 't_ group_member'
Where c_valid in (3, 4)
Group by c_group_id;
Declare continue handler for not found set stopflag = 1;
Open cursor_name;
Repeat
Fetch cursor_name into p_group_id, p_num;
Begin
Update t_groupinfo set c_member_number = p_num where c_group_id = p_group_id;
End;
Until stopflag = 1
End repeat;
Close cursor_name;
End;

Summary:
1. Pay attention to the countinue handler: declare continue handler for not found set stopflag = 1;
2. Pay attention to the use of repeat and utile [Stop Condition] End repeat, otherwise it will not be cyclically;
3. Run the following command: Call justifygroupnum ()

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.