標籤:
一、概述
預存程序是資料庫定義的一些SQL語句的集合,然後直接調用這些預存程序和函數來執行已經定義好的SQL語句。預存程序可以避免開發人員重複的編寫相同的SQL語句,而且預存程序是在MySql伺服器中儲存和執行的,可以減少用戶端與伺服器端的資料轉送。
1.優點
(1)提供執行效能
通常在用戶端執行SQL命令時,在資料庫有解析到編譯這個前期準備過程。但是,預存程序是先完成瞭解析、編譯的處理後儲存在資料庫中的,執行時能減輕資料庫負擔,提高執行效能。
(2)可減輕網路負擔
使用預存程序後,複雜的資料庫操作也可以在資料庫伺服器中完成,只要從應用程式傳遞給資料庫必要的參數就行,比起多次傳遞SQL命令,這大大減輕了網路負擔。
二、基本操作 1.定義預存程序
#建立預存程序create procedure p1()begin select * from t_user;end
2.調用預存程序
#調用預存程序call p1();
3.查看預存程序
#查看預存程序show procedure status;
4.刪除預存程序
#刪除預存程序drop procedure p1;
5.建立帶參數的預存程序
#1.建立帶參數的預存程序create procedure p2(i int)begin select * from t_user where id > i;end#2.調用帶參數的預存程序call p2(3);
結果:
6.建立帶判斷語句的預存程序
#1.建立帶判斷語句的預存程序create procedure p3(i int,j char(10))begin if j = ‘high‘ then select * from t_user where id > i; elseif j = ‘low‘ thenselect * from t_user where id < i; end if; end#2.調用帶選擇結構的預存程序call p3(3,‘low‘);
結果:
7.使用case命令使用多重條件陳述式
#1.使用case命令多重條件分支create procedure p4(i int)begin case i when 1 then select * from t_user where address=‘北京‘; when 2 then select * from t_user where address=‘上海‘; else select * from t_user where address=‘吉林‘; end case;end#2.查看結果call p4(2);
結果:
8.建立局部變數
#1.建立局部變數create procedure p5(i int)begin declare temp varchar(10);case i when 1 then set temp = ‘北京‘;when 2 then set temp = ‘上海‘;when 3 then set temp = ‘吉林‘;end case;select * from t_user where address= temp;end#2.查看結果call p5(3);
結果:
MySQL學習筆記(四)—預存程序