MySQL遊標的使用

來源:互聯網
上載者:User

標籤:ar   os   使用   for   sp   on   bs   ef   as   

  1. MySQL遊標的使用  
  2.  
  3. A simple cursor of mysql  
  4.  
  5. step1:  
  6. 建立表tb_test;  
  7.  
  8. create table tb_test(  
  9.    id int  
  10. );  
  11.  
  12. insert into tb_test values (‘1‘);  
  13. insert into tb_test values (‘2‘);  
  14. insert into tb_test values (‘3‘);  
  15.  
  16. step2:  
  17. 聲明預存程序sp_test;  
  18.  
  19. delimiter $$    
  20. create procedure sp_test()    
  21. BEGIN    
  22.    declare tmp int default 0;  
  23.    declare sum int default 0;  
  24.    declare done int default -1;  
  25.      
  26.    /* 聲明遊標 */  
  27.    declare myCursor cursor for select id from tb_test;  
  28.      
  29.    /* 當遊標到達尾部時,mysql自動化佈建done=1 */    
  30.    declare continue handler for not found set done=1;  
  31.      
  32.    /* 開啟遊標 */  
  33.    open myCursor;  
  34.      
  35.    /* 迴圈開始 */  
  36.    myLoop: LOOP  
  37.      
  38.        /* 移動遊標並賦值 */  
  39.        fetch myCursor into tmp;  
  40.          
  41.        if done = 1 then  
  42.        leave myLoop;  
  43.        end if;  
  44.          
  45.        /* do something */  
  46.        set sum = sum + tmp;  
  47.      
  48.    /* 迴圈結束 */  
  49.    end loop myLoop;  
  50.      
  51.    insert into tb_test values(sum);  
  52.      
  53.    /* 關閉遊標 */  
  54.    close myCursor;  
  55. END    
  56. $$    
  57. delimiter ;  
  58.  
  59. step3:  
  60. call sp_test();  
  61. select * from tb_test();  
  62. +----+    
  63. | id |    
  64. +----+    
  65. |  1 |    
  66. |  2 |    
  67. |  3 |  
  68. |  6 |    
  69. +----+

MySQL遊標的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.