MySQL的儲存過程中使用游標來接收查詢結果集

2021-10-07 07:21:01 字數 2141 閱讀 9536

我們如果要在mysql的儲存過程中遍歷乙個查詢語句的結果集,需要使用到游標cursor(sql server中可以定義表型別的變數table,但mysql中不行,只能用游標)。

假設我需要從 tb_stu 這張表中查詢出所有記錄插入到tb_stu_copy1中,等價於insert into tb_stu_copy1 select * from tb_stu;

以下是儲存過程的具體sql

create

procedure curdemo (

)begin

declare stop_flag int

default0;

declare this_id int

;declare this_name varchar

(100);

declare this_*** varchar(2

);declare cu cursor

forselect

*from tb_stu;

declare

continue

handler

for sqlstate '02000'

set stop_flag =1;

#當fetch游標到了結果即最後一行的時候,設定stop_flag=1

open cu;

#定義完游標之後要開啟游標

fetch cu into this_id, this_name, this_***;

#讀取資料到游標

while

stop_flag <>1do

insert

into tb_stu_copy1

values

( this_id, this_name, this_*** )

;fetch cu into this_id, this_name, this_***;

endwhile

;close cu;

#關閉游標

end

我們使用游標的公式步驟大概如下:

定義游標變數declare 游標變數名 cursor for 查詢語句定義乙個當游標移動到末尾時執行的操作declare continue handler for sqlstate '02000' 具體操作**開啟游標open 游標變數名fetch關鍵字存查詢結果集中獲取資料

迴圈遍歷(注意mysql儲存過程中不能用for迴圈)

關閉游標close 游標變數名

這裡有一段**值得注意

declare

continue

handler

for sqlstate '02000'

set stop_flag =

1;

這句話是宣告了乙個控制代碼,當 sqlstate 的值為』02000』 時會執行這個控制代碼,從而使stop_flag設定為1。而sqlstate '02000'是什麼意思呢?sqlstate正常狀態是返回』00000』的,當發生下述異常之一時,sqlstate就會變成02000

上述的第三種異常是符合我們的情況的。也就是說,將在遍歷完所有結果集之後就會呼叫sqlstate變成02000。

關於sqlstate更多的狀態碼,可以檢視這篇部落格:

這裡邊有乙個關鍵字continue,這個關鍵字和exit關鍵字相對應的。continue語句執行完指定操作後繼續迴圈,而exit語句會從最近的begin...end語句塊中退出。這裡指定的操作就是set stop_flag = 1。我們給 stop_flag 設定為1之後continue就會繼續迴圈,然後迴圈條件判斷發現stop_flag <>1 不滿足,於是while迴圈就結束了

注意:控制代碼要定義在游標之後, 不然會報1338 - cursor declaration after handler declaration錯誤。

儲存過程中使用游標

create proc cursortest id int 0,name varchar 50 as 建立游標 declare cursor cursor 設定游標欲操作的資料集 set cursor cursor for select id,name from users 開啟游標 open cu...

在Oracle過程中使用游標

create or replace procedure ss c002 tm14to13 p errcode out number,p errtext out varchar2 is isbn轉換條碼,14位錯誤的轉換成13位正確的 yc2008 04 18 cursor c gckc is sel...

Mysql 儲存過程使用游標

完整例子 create procedure test begin 定義引數 declare id int 定義游標 declare no more products int default 0 declare result test cursor for select num1 from numte...