寫在前面:
文章整理上傳於2017年9月26日 ,
是博主學習燕十八的視頻後自己整理的筆記 ,如果有錯誤,你來打我呀
主要是存儲過程的簡單使用 ,至於什麼是存儲過程,爲什麼用過程,什麼時候用過程,網上有好多,我不想在這裏寫了.
1.存儲過程語法:
create procedure 過程名稱(參數)
begin
//核心代碼
end;
最簡單的示例:
create procedure p1()
begin
select 'hello world';
end;
--調用:
call p1;
2.聲明變量
語法:declare 變量1 類型 default 默認值 ;
例:create procedure p1()
begin
declare age int default 18;
select age ;
end;
2.運算與變量賦值
賦值語法: set 變量名 := 運算 ;create procedure p1()
begin
declare age int default 18;
set age := age + 20 ;
select age ;
end;
3.邏輯控制 if-end if
--格式:
if 表達式 then
--核心代碼;
end if ;
--例:
create procedure p1()
begin
declare age int default 18;
set age := age + 20 ;
if age>20 then
select '你>20了' ;
else if age<20 then
select '你<20' ;
else
select '你=20';
end if ;
end;
4.傳參數,輸入輸出
--格式:
[in/out/inout] 參數名稱 類型 ,.....
--示例:
create procedure p1(in height int,in width int,out chengji)
begin
set chengji := height * width ;
if height>width then
select '你高>寬' ;
else if height<width then
select '高<寬' ;
else
select '高=寬';
end if ;
end;
--調用:
set @height :=10;
set @width :=20;
set @chengji :=0;
call p1(@height,@width,@chengji);
select @chengji;
5.流程控制 while
--格式:
while 表達式 do 核心代碼 end while;
--例:
create procedure p1(in i int)
begin
while i>0 do
select i;
set i := i-1;
end while;
end;
--調用:
call p1(10);
6多條件分支 case
語法:
case 變量 when 值1 then 核心代碼 ;
when 值2 then 核心代碼 ;
else 核心代碼 ;
end case ;
7.repeat循環
--語法:
repeat 核心代碼 until 表達式 end repeat ;
--例:
create procedure p1(in i int)
begin
while i>0 do
select i;
set i := i-1;
end while;
end;
8.0 遊標 (sql數據處理 )
--一條sql對應n個資源 ,取出資源的句柄/接口 就是遊標--沿着遊標 ,可以一行一行的取出數據
--declare 聲明遊標,格式: declare 遊標名稱 cursor for select statement
--open 打開,格式: open 遊標名稱
--fetch 取值,格式: fetch 有標明 into var1,var2....
--close 關閉,格式: close 遊標名稱
--使用遊標 ,主要是爲了實現對數據的控制 ,控制數據進行改變數據,編程
8.1 存儲過程中的遊標(簡單示例)
create procedure p1()
begin
declare rowid int;
declare rownum int;
declare rowname varchar(20);
declare getgoods cursor for select *from good;--聲明
open getgoods;
fetch getgoods into rowid,rownum,rowname;--取出賦值一次 ,可以循環多次直到遊標到頭(如何循環取出多行??)
close getgoods;--關掉
select rowid,rowname,rownum;--打印數據
end
8.2 遊標+循環取出數據,越界標誌
思路1:定義一個變量 count,使得count=總行數 ,然後while判斷之類的直到fetch到count計數跳出思路2:mysql的cursor中可以用declare continue handler 來操作一個越界標示
--declare continue handler for NOT FOUND set 越界變量 = 1 ;
--相當於發生越界404就把越界變量賦值爲0;
--代碼(sl2):
create procedure p1()
begin
declare rowid int;
declare rownum int;
declare rowname varchar(20);
declare getgoods cursor for select *from good;--聲明
declare yuejie int declare 0;--越界變量
declare continue handler for NOT FOUND set yuejie :=1;--越界變量
open getgoods;
repeat --循環開始
fetch getgoods into rowid,rownum,rowname;--取出賦值
select rowid,rowname,rownum;--打印數據()
until yuejie = 1 end repeat; --循環結束
close getgoods;--關掉
end
需完善的地方: 可能取出第一次就出現404 ,應當先fetch一次 實際上,用while符合邏輯語義
當觸發404 ,select仍會執行 ,select的數據爲上次fetch的數據(緩存,暫且這樣說)
8.2handler
continue: 觸發後繼續執行後續語句exit: 觸發後後續不在執行
undo: 觸發後,前面的語句撤銷(版本是否支持,有待考證)
9.後續補充
暫無.