1 什麼是存儲過程
- 簡單的說,就是一組SQL語句集,功能強大,能夠實現一些比較複雜的邏輯功能,相似於JAVA語言中的方法;
- ps:存儲過程跟觸發器有點相似,都是一組SQL集,可是存儲過程是主動調用的,且功能比觸發器更增強大,觸發器是某件事觸發後自動調用。
2 有哪些特性
- 有輸入輸出參數,能夠聲明變量,有if/else, case,while等控制語句,經過編寫存儲過程,能夠實現複雜的邏輯功能;
- 函數的廣泛特性:模塊化,封裝,代碼複用;
- 速度快,只有首次執行需通過編譯和優化步驟,後續被調用能夠直接執行,省去以上步驟。
3 建立一個簡單的存儲過程
- 存儲過程proc_adder功能很簡單,兩個整型輸入參數a和b,一個整型輸出參數sum,功能就是計算輸入參數a和b的結果,賦值給輸出參數sum
幾點說明
- DELIMITER ;; :以前說過了,把默認的輸入的結束符;替換成;;。
- DEFINER:建立者;
-- ----------------------------
-- Procedure structure for `proc_adder`
-- ----------------------------
DROP PROCEDURE IF EXISTS `proc_adder`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_adder`(IN a int, IN b int, OUT sum int)
BEGIN
#Routine body goes here...
DECLARE c int;
if a is null then set a = 0;
end if;
if b is null then set b = 0;
end if;
set sum = a + b;
END
;;
DELIMITER ;
執行以上存儲結果,驗證是否正確:
set @b=5;
call proc_adder(2,@b,@s);
select @s as sum;
若是結果 sum = 7;
ok
4 存儲過程當中的控制語句
IF語句:
-- ----------------------------
-- Procedure structure for `proc_if`
-- ----------------------------
DROP PROCEDURE IF EXISTS `proc_if`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_if`(IN type int)
BEGIN
#Routine body goes here...
DECLARE c varchar(500);
IF type = 0 THEN
set c = 'param is 0';
ELSEIF type = 1 THEN
set c = 'param is 1';
ELSE
set c = 'param is others, not 0 or 1';
END IF;
select c;
END
;;
DELIMITER ;
執行以上存儲結果,驗證是否正確:
set @type=1;
call proc_if(@type);
若是結果 c = param is 1;
ok
CASE語句:
-- ----------------------------
-- Procedure structure for `proc_case`
-- ----------------------------
DROP PROCEDURE IF EXISTS `proc_case`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_case`(IN type int)
BEGIN
#Routine body goes here...
DECLARE c varchar(500);
CASE type
WHEN 0 THEN
set c = 'param is 0';
WHEN 1 THEN
set c = 'param is 1';
ELSE
set c = 'param is others, not 0 or 1';
END CASE;
select c;
END
;;
DELIMITER ;
執行以上存儲結果,驗證是否正確:
set @type=1;
call proc_case(@type);
若是結果 c = param is 1;
ok
循環while語句:
-- ----------------------------
-- Procedure structure for `proc_while`
-- ----------------------------
DROP PROCEDURE IF EXISTS `proc_while`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_while`(IN n int)
BEGIN
#Routine body goes here...
DECLARE i int;
DECLARE s int;
SET i = 0;
SET s = 0;
WHILE i <= n DO
set s = s + i;
set i = i + 1;
END WHILE;
SELECT s;
END
;;
DELIMITER ;
執行以上存儲結果,驗證是否正確:
set @type=100;
call proc_while(@type);
若是結果 s = 5050;
ok
5 存儲過程弊端
- 不一樣數據庫,語法差異很大,移植困難,換了數據庫,須要從新編寫;
- 很差管理,把過多業務邏輯寫在存儲過程很差維護,不利於分層管理,容易混亂,通常存儲過程適用於個別對性能要求較高的業務,其它的必要性不是很大。