Mysql存儲過程詳解及案例


Mysql存儲過程:
1.1 定義:把復雜的操作,封裝一個過程。類似於函數。
優點:
1、復雜操作,調用簡單。
2、速度快。
缺點:
1、封裝復雜。
2、沒有靈活性。

1.2 查看所有存儲過程命令:
1 show procedure status;
查看存儲過程或函數的創建代碼:
1 show create procedure proc_name;
2 show create function func_name;
調用存儲命令:
1 call 名稱;
刪除存儲過程命令:
1 DROP {PROCEDURE | FUNCTION} [IF EXISTS] 名稱;
創建存儲過程:
1 create procedure 名稱(參數,.....)
2             begin
3                 過程體;
4                 過程體;
5             end//
參數:
1 in|out|inout 參數名稱 類型(長度)
在sql語句中給變量賦值:
1 into
在過程體外聲明變量:
1 @變量名
重新制定sql語句的結束符:
1 delimiter //
例子:獲取5條文章記錄
1 create procedure getNews()
2     begin
3         select * from news limit 5;
4     end//
例子:獲取n條文章記錄
1 create procedure getNewsN(in n int(5))
2     begin
3         select * from news limit n;
4     end//
例子:獲取某欄目下文章的條數。
1 create procedure getNewsByType(in fid int,out num int)
2     begin
3         select count(*) into num from news where fcid=fid;
4     end//
聲明變量:
1 declare 變量名 類型(長度) default 默認值;
給變量賦值:
1 set 變量名=值;
說明:
強類型。
例子:
1 create procedure test()
2     begin
3         declare a int default 5;
4         declare b int default 6;
5         declare c int default 0;
6         set c=a+b;
7         select c as num;
8     end//
1.3 條件語句

 1 if 條件 then
 2    語句;
 3 else
 4    語句;
 5 end if;
 6 
 7 if 條件 then
 8    語句;
 9 elseif 條件 then
10    語句;
11 .....
12 else
13 
14 end if;
15 
16 循環語句
17 while 循環條件  do
18    循環體;
19    變換步長;
20 end while;
例子:輸出1到10之間偶數
 1 create procedure oshu()
 2     begin
 3         declare i int default 1;
 4         while i<11 do
 5             if i%2 = 0  then
 6                 select i;
 7             end if;
 8             set i=i+1;
 9         end while;
10     end//
例子:使用存儲過程實現 購物
 1 create procedure buy1(in pidn int,in uidn int,in numn int)
 2 begin
 3    declare jiage float(7,2) default 0.00;
 4    declare zongjia float(9,2) default 0.00;
 5    declare e tinyint(1) default 0;
 6    declare continue handler for SQLEXCEPTION set e=1;
 7    -- 獲取價格
 8    select price into jiage from productn where pid=pidn;
 9    -- 算出總價
10    set zongjia=jiage*numn;
11    -- 開啟事務
12    start transaction;
13    -- 扣款
14    update usern set money=money-zongjia where uid=uidn;
15    -- 出庫
16    update productn set num=num-numn where pid=pidn;
17    -- 判斷是否有異常
18    if e=1 then
19       rollback;
20       select 0 as re;
21    else
22       commit;
23       select 1 as re;
24    end if;
25 end//
獲取異常:
1 declare continue handler for SQLEXCEPTION set e=1;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM