第二十三章 使用存储过程

注:一个数据库小白的成长之路

执行存储过程

CALL productpricing(@pricelow,
                    @pricehigh,
                    @priceaverage);

执行名为productpricing的存储过程,它计算并返回产品的最低、最高和平均价格。

创建存储过程

CREATE PROCEDURE productpricing()
BEGIN
     SELECT AVG(prod_price) AS priceaverage 
     FROM products;
END;

BEGIN和END语句用来限定存储过程体

删除存储过程

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)
     FROM products
     INTO pl;
     SELECT MAX(prod_price)
     FROM products
     INTO ph;
     SELECT AVG(prod_price)
     FROM products
     INTO pa;
END;

-- 使用存储过程
CALL productpricing(@pricelow,
                    @pricehigh,
                    @priceaverage);
SELECT @pricelow, @pricehigh, @priceaverage;

关键字IN表示将参数传递给存储过程,OUT表示参数从存储过程中传出。

-- 创建存储过程
CREATE PROCEDURE ordertotal(
     IN onumber INT,
     OUT ototal DECIMAL(8, 2)
)
BEGIN
     SELECT SUM(item_price*quantity)
     FROM orderitems
     WHERE order_num = onumber
     INTO ototal;
END;

-- 调用存储过程
CALL ordertotal(20005, @total);

-- 显示结果
SELECT @total;

建立智能存储过程

-- 创建
CREATE PROCEDURE ordertotal(
     IN onumber INT,
     IN taxable BOOLEAN,
     OUT ototal DECIMAL(8, 2)
)
BEGIN
     DECLARE total DECIMAL(8, 2);
     DECLARE taxrate INT DEFAULT 6;
     SELECT SUM(item_price*quantity)
     FROM orderitems
     WHERE order_num = onumber
     INTO total;
     IF taxable THEN
        SELECT total+(total/100*taxrate) INTO total;
     END IF;
     SELECT total INTO ototal;
END;

-- 使用
CALL ordertotal(20005, 1, @total);
SELECT @total;

注意:

  • 所有MySQL变量都必须以@开始
  • 用DECLARE语句定义两个局部变量,DECLARE要求指定变量名和数据类型,它也支持可选的默认值。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。