MySQL 預存程序遊標

來源:互聯網
上載者:User

標籤:style   blog   io   color   ar   os   使用   for   sp   

一、建立遊標

遊標用declare語句建立。如下面的例子所示:

create procedure test2()begin    declare cursorTest cursor    for    select * from allIntersection;end;
二、開啟、關閉遊標
  • 開啟遊標
    open cursorTest;  
  • 關閉遊標
    close cursorTest;  

     CLOSE釋放遊標使用的所有內部記憶體和資源,因此在每個遊標不再需要時都應該關閉。在一個遊標關閉後,如果沒有重新開啟,則不能使用它。但是,聲明過的遊標不需要再次聲明,用OPEN語句開啟它就可以了。

三、使用遊標資料

在一個遊標被開啟後,可以使用FETCH語句分別訪問它的每一行。FETCH語句指定檢索什麼資料(所需的列),檢索出來的資料存放區在什麼地方。它還向前移動遊標中的內部行指標,使下一條FETCH語句檢索下一行(不重複讀取同一行)。

create procedure test3()begin    declare o int;            -- 聲明一個局部變數  declare cursorTest3 cursor        -- 聲明一個遊標    for      select ID    from allintersection;    open cursorTest3;          -- 開啟遊標    fetch cursorTest3 into o;              -- 擷取IntersectionName    close cursorTest3;  -- 關閉遊標end;

其中FETCH用來檢索當前行的IntersectionName列(將自動從第一行開始)到一個名為o的局部聲明的變數中。對檢索出的資料部做任何處理

四、式例
create procedure test4()begin    declare done boolean default 0;    declare o int;            -- 聲明一個局部變數  declare cursorTest4 cursor        -- 聲明一個遊標    for      select ID    from allintersection;  declare continue handler for sqlstate ‘02000‘ set done=1;    open cursorTest4;          -- 開啟遊標    -- 遍曆所有的行    repeat           fetch cursorTest4 into o;              -- 擷取IntersectionName    until done end repeat;           -- 結束迴圈    close cursorTest4;  -- 關閉遊標end;

 

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.