mysql儲存過程的學習(二)

2022-02-23 04:31:16 字數 1095 閱讀 4145

游標的使用

儲存過程裡面,如果查詢到的結果,是乙個集合,如果我們要從這個集合裡面篩選出來一部分我們需要的資料,就會用到游標

因為游標乙個結果集 然後乙個結果乙個結果的遍歷,然後在每乙個結果裡面去拿你想要的東西

創造乙個帶有游標的儲存過程

create procedure `zhenyoubiao`()

begin-- 首先我們需要定義幾個引數這幾個引數主要是用來儲存我們想要的東西,

-- 定義接受游標裡面的資料

declare i int default 0;

declare cur_username varchar(20);

declare cur_age int default 0;

-- 這裡的_stop 主要是為了判斷當我們遍歷游標的時候發現沒有結果 直接就把迴圈結束了

declare _stop int default 0;

-- 這裡的wonima 就是建好的游標  我們把查詢到的資料直接放到這個游標裡面去

declare wonima cursor for

select user_name,age from u_user where id =2;

-- 定義遍歷的時候游標裡面沒有資料直接就停止

declare continue handler for not found set _stop=1;

-- 開啟游標

open wonima;

-- 使用while迴圈進行遍歷

while _stop<>1 do

-- 提取游標裡面的值

fetch wonima into cur_username,cur_age;

-- 對這一行結果進行操作

insert into u_user (user_name,age)values(cur_username,cur_age);

set i=i+1;

-- 結束while迴圈

end while;

-- 結束游標

close wonima;

end;

呼叫這個儲存過程

call zhenyoubiao();

給個鏈結裡面有遍歷游標的方式

MySQL儲存過程的學習(二)

在 一 中完成了對儲存過程的增刪改查,接下來學習下怎麼使用儲存過程 1.儲存過程的呼叫 無參 儲存過程呼叫的時候使用的call 語法為call procedure name 如 call proc demo 2.儲存過程的呼叫 帶參 語法為call procedure name 引數列表 首先建立乙...

mysql 儲存過程學習 mysql儲存過程學習

一 mysql建立乙個修改表字段的儲存過程 drop procedure if exists pr test create procedure pr test begin declare var int declare var1 int set var 416 set var1 420 while ...

學習筆記 MySql儲存過程學習二

delimiter create procedure p showage two age int begin ifage 18 then select 成年人 else select 未成年人 endif end create procedure p showage two in age int b...