Use of MySQL Cursors

Source: Internet
Author: User

  1. Use of MySQL Cursors
  2. A simple cursor of MySQL
  3. Step1:
  4. New Table tb_test;
  5. CREATE TABLE Tb_test (
  6. ID int
  7. );
  8. INSERT into tb_test values (' 1 ');
  9. INSERT into tb_test values (' 2 ');
  10. INSERT into tb_test values (' 3 ');
  11. Step2:
  12. Declares the stored procedure sp_test;
  13. Delimiter $$
  14. CREATE PROCEDURE Sp_test ()
  15. BEGIN
  16. DECLARE tmp int default 0;
  17. DECLARE sum int default 0;
  18. DECLARE done int default -1;
  19. / * Declare a cursor * /
  20. DECLARE mycursor cursor for select id from tb_test;
  21. / * When the cursor reaches the tail, MySQL automatically sets done=1 * /
  22. Declare continue handler for not found set done=1;
  23. / * OPEN cursor * /
  24. Open mycursor;
  25. / * Cycle start * /
  26. Myloop:loop
  27. / * Move cursor and assign value * /
  28. Fetch mycursor into TMP;
  29. if do = 1 Then
  30. Leave Myloop;
  31. End if;
  32. / * do something * /
  33. Set sum = SUM + tmp;
  34. / * End of Loop * /
  35. End Loop Myloop;
  36. INSERT into tb_test values (sum);
  37. / * Close the cursor * /
  38. Close MyCursor;
  39. END
  40. $$
  41. delimiter;
  42. Step3:
  43. Call Sp_test ();
  44. SELECT * from Tb_test ();
  45. +----+
  46. | ID |
  47. +----+
  48. | 1 |
  49. | 2 |
  50. | 3 |
  51. | 6 |
  52. +----+

Use of MySQL Cursors

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.