用戶變量一般以@開頭,作用於全局范圍
局部變量需用 declare 定義格式為 declare 變量名 數據類型 [default value];
mysql 數據類型有 int ,float,date,varchar(length)等
聲明的順序必須是 先聲明變量,再聲明游標、最后聲明handler。
同一個存儲過程中,一個游標的使用和兩個游標的使用是一樣的。
調用存儲過程 call sp_name();
查詢某數據庫中全部存儲過程 :
select name from mysql.proc where db='數據庫名';
或
select routine_name from information_schema.routines where routine_schema='數據庫名';
或
show procedure status where db='數據庫名';
查看單個存儲過程: show create procedure 數據庫.存儲過程名;
刪除存儲過程 :drop procedure 存儲過程名
存儲過程創建語句:
delimiter $$ -- 定義語句結束標志為 $$, 默認結束標志是;
drop procedure if exists test.sp_example$$ -- 創建存儲過程關鍵字
create procedure test.sp_example() -- 創建存儲過程具體內容:
begin -- 存儲過程內容以begin開始,end 結束。
declare _inner_code int; -- 聲明 局部變量 及變量類型
declare _writedate date;
declare _done int default 1; -- 聲明 局部變量 、變量類型 及 變量默認值
declare c_cursor cursor for select inner_code,writedate from test.example group by inner_code,writedate;
-- 聲明游標名、游標所存儲數據
-- 此處可繼續申明第二個游標 : declare a_cursor cursor for select ... from ...;
declare continue handle for not found set _done=0; -- 當出現 not found 的錯誤時 continue 並將變量_done的值設置為0
start transaction;
open c_cursor; -- 打開游標
fetch c_cursor into _inner_code,_writedate;
-- 獲取當前游標指向的數據行賦值給變量_inner_code,_writedate,並將游標指向下一行
while _done do
功能語句塊
fetch c_cursor into _inner_code,_writedate;
/* 獲取當前游標指向的數據行賦值給變量_inner_code,_writedate,並將游標指向下一行,當游標已經指向最后一行時會造成游標溢出. mysql 中游標溢出時會引發mysql預定義的not found 錯誤,在上面定義了一個continue屬性的操作handle,當出現not found 錯誤時 繼續,並修改_done變量的值為0,使循環結束*/
end while ;
close c_cursor ; -- 關閉游標
end $$
delimiter ; -- 將結束標志定義回;
游標嵌套
在mysql中同一個error事件只能定義一次,如果多定義的話在編譯時會提示 duplicate handler declared in the same block.
每個begin end 塊都是一個獨立的scope 區域,嵌套的游標可用begin end 包裹。
drop procedure if exists nest_use;
create procedure nest_use()
begin
declare _n varchar(20);
declare done int default false;
declare cur cursor for select age from store group by age;
declare continue handler for not found set done =true;
open cur ;
read_loop:loop
fetch cur into _n;
if done then
leave read_loop;
end if ;
begin
declare c int ;
declare n varchar(20);
declare total int default 0;
declare done int default false;
declare cur cursor for select name ,count from store where name='iphone';
declare continue handler for not found set done=true;
set total=0;
open cur ;
iphone_loop:loop
fetch cur into n ,c ;
if done then
leave iphone_loop;
end if ;
set total =tatal + c;
end loop;
close cur;
select _n,n,total;
end;
begin
declare c int;
declare n varchar(20);
declare total int default 0;
declare done int default false;
declare cur cursor for select name,count from store where name = 'android';
declare continue HANDLER for not found set done = true;
set total = 0;
open cur;
android_loop:loop
fetch cur into n,c;
if done then
leave android_loop;
end if;
set total = total + c;
end loop;
close cur;
select _n,n,total;
end;
end loop;
close cur;
end ;