(12)mysql中的游標,12mysql中游標

來源:互聯網
上載者:User

(12)mysql中的游標,12mysql中游標
概述

查詢語句可能查詢出多條記錄,在預存程序和函數中使用游標來逐條讀取查詢結果集中的記錄。有些書上將游標稱為遊標。游標的使用包括聲明游標、開啟游標、使用游標和關閉游標。游標必須聲明在處理常式之前,並且聲明在變數和條件之後。游標可以類比為數組內部中的迴圈指標。

聲明游標
declare cursor_name cursor for select_statement;

其中,cursor_name參數表示游標的名稱;select_statement參數表示SELECT語句的內容。

聲明游標舉例

DECLARE cur_employee SELECT name, age FROM employe;

上面的樣本中,聲明一個名為cur_employee的游標。游標的名稱為cur_employee;SELECT語句部分是從employee表中查詢出name和age欄位的值。

開啟游標
open cursor_name;
使用游標
fetch cursor_name into var_name[,var_name]...

其中,cursor_name參數表示游標的名稱;var_name參數表示將游標中的SELECT語句查詢出來的資訊存入該參數中。var_name必須在聲明游標之前就定義好。

關閉游標
close cursor_name;

關閉之後就不能使用FETCH來使用游標了。

游標在預存程序或函數中的使用

目前,mysql中的游標只能在預存程序或函數中使用。

相關文章

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.