存储过程
什么是存储过程:
存储过程简单来说,就是为以后的使用而保存的一条或多条MySQL语句的集合;
存储过程需要MySQL 5 版本以后支持;
如何检查MySQL版本:使用命令 status 或者 缩写 \s
为什么要使用存储过程
1、简化操作流程,
2、使用复用的操作过程,确保了安全性,
3、减少对数据的改动,
4、提高处理性能,
5、更加灵活的处理数据。
使用存储过程
引入CALL 语句;
MySQL称存储过程的执行为调用,因此MySQL执行存储过程的语句为CALL。
执行存储过程
CALL productpricing();
创建存储过程
创建存储过程,作为一名菜鸟,在教材的辅助下,一直报错:
CREATE PROCEDURE productpricing() BEGIN SELECT Avg(prod_price) AS priceaverage FROM products; END;
报错信息为:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END' at line 1
如何解决,创建存储过程中遇到的语法报错呢?
解决方法:解决办法是临时更改命令行实用程序的语句分隔符;
执行完上述的创建过程一定要记得,还原分隔符定义
否则就变成,双斜线执行了;
删除存储过程
DROP PROCEDURE productpricing;
使用参数
CREATE PROCEDURE productpricing( OUT pl DECIMAL(8,2), OUT ph DECIMAL(8,2), OUT pa DECIMAL(8,2) ) BEGIN SELECT Min(prod_price) INTO pl FROM products; SELECT Max(prod_price) INTO ph FROM products; SELECT Avg(prod_price) INTO pa FROM products; END//
上面的存储过程定义了三个输出参数;
调用存储过程时,入参对应的低价、高价、平均价;分别对应创建存储过程的select 低 、高 、平均;
以上的例句中只使用了OUT参数;
接下来的例句中将使用IN 和 OUT 参数
调用存储过程,入参选择order_number = 20005 ; SELECT 输出语句计算出结果ototal 定义为@total输出;
建立智能存储过程
以下建立了一个只能的存储过程,可以动态添加以及变化要素;
-- Name: ordertotal
-- Parameters: onumber = order number
-- taxable = 0 if not taxable, 1 if taxable
-- ototal = order total variable
CREATE PROCEDURE ordertotal(
IN onumber INT,
IN taxable BOOLEAN,
OUT ototal DECIMAL(8,2)
) COMMENT 'Obtain order total, optionally adding tax'
BEGIN
-- Declare variable for total
DECLARE total DECIMAL(8,2);
-- Declare tax percentage
DECLARE taxrate INT DEFAULT 6;
-- Get the order total
SELECT Sum(item_price*quantity) FROM orderitems WHERE order_num = onumber INTO total;
-- Is this taxable?
IF taxable THEN
-- Yes, so add taxrate to the total
SELECT total+(total/100*taxrate) INTO total;
END IF;
-- And finally, save to out variable
SELECT total INTO ototal;
END//
不同的入参 ,输出结果不同;
检查存储过程
SHOW CREATE PROCEDURE ordertotal//
我这里的命令由于我没有将分隔符定义复原为分号,所以仍然用双斜线确认;