MySQL 游標和儲存過程

2021-08-13 22:49:12 字數 1540 閱讀 9665

/*我們有時候會遇到需要對 從a表查詢的結果集s_s 的記錄 進行遍歷並做一些操作(如插入),且這些操作需要的資料或許部分來自s_s集合*/

/*臨時儲存過程,沒辦法,不能直接在查詢視窗做這些事。*/

drop procedure

ifexists proc_tmp;

create procedure proc_tmp()

begin

/*這種寫法也可以:declaredoneintdefaultfalse;*/

declare done

intdefault

0; /*用於判斷是否結束迴圈*/

declare hostid bigint; /*用於儲存結果集s_s的記錄(因為我這裡s_s的記錄只有一列且為bigint型別)*/

/*定義游標*/

declare idcur cursor

forselect a.hostid from dev_host as a, sys_hostconfig as b where a.hostid !=b.hostid;

/*定義 設定迴圈結束標識done值怎麼改變 的邏輯*/

declare

continue

handler

fornot found set done = 1

; /*done = true;亦可*/

open idcur; /*開啟游標*/

/* 迴圈開始 */

repeat

/* 如果要fetch多列應該這樣寫,fetch cur/*對應下面的idcur*/ into rowid, rowname;但是注意rowid和rowname要先declare,且declare cur時也要select兩列,且這兩列和rowid、rowname對應 */

fetch idcur into hostid; /*這部分可以看看書,還可以fetch多列(假設結果集s_s的記錄不是單列的話)*/

ifnot done then /*數值為非0,mysql認為是true*/

insert into sys_hostconfig(hostid, aeleccap, beleccap, celeccap, remeleccap, atmpcap, btmpcap, ctmpcap, boxtmpcap, createtime)

/*注意這裡用到了hostid和now()*/

values(hostid,

80, 80, 80, 500, 80, 80, 80, 80

, now());

endif

;until done end repeat;

close idcur; /*關閉游標*/

end/* 迴圈結束 */

call proc_tmp();

drop procedure proc_tmp; /*刪除臨時儲存過程*/

mysql 游標 儲存過程

1.首先需要注意的是mysql中游標必須要建立在儲存過程中 2.直接上sql 查詢當天資料 select in flow out flow from water meter data where 1 1 and date sys read time curdate 1 order by in flo...

MySQL 儲存過程 游標

儲存過程 本儲存過程有特殊執行迴圈數量的要求,是對security market history表進行修正 判斷儲存過程是否存在 drop procedure if exists proc security market history update create procedure proc se...

mysql 儲存過程 游標

宣告游標 declare cursor name cursor for select statement 這個語句宣告乙個游標。也可以在子程式中定義多個游標,但是乙個塊中的每乙個游標必須有唯一的名字。開啟游標 open cursor name 這個語句開啟先前宣告的游標。游標fetch fetch ...