《MySQL必知必会》第二十三章-使用存储过程

执行存储过程

CALL productpricing(@pricelow,
                    @pricehigh,
                    @priceaverage); -- 所有MySQL变量都必须以@开始


创建存储过程

DELIMITER //  -- 告诉命令行实用程序使用//作为新的语句结束分隔符
CREATE PROCEDURE productpricing()
BEGIN
    SELECT Avg(prod_price) AS priceaverage
    FROM products;
END //
DELIMITER ;  -- 恢复为原来的语句分隔符
-- CALL productpricing();

删除存储过程

DROP PROCEDURE productpricing;
DROP PROCEDURE IF EXISTS productpricing;

使用参数


MySQL支持IN(传递给存储过程)、OUT(从存储过程传出)、INOUT(对存储过程传入和传出) 类型的参数
DELIMITER //
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//
DELIMITER ;
-- CALL productpricing(@pricelow, @pricehigh, @priceaverage);
-- SELECT @pricehigh, @pricelow, @priceaverage;

DELIMITER //
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 //
DELIMITER ;
-- CALL ordertotal(20005, @total);
-- SELECT @total;

建立智能存储过程

-- Name: ordertotal
-- Parameters: onumber = order number
            -- taxable = 0 if not taxable, 1 if taxable
            -- ototal = order total variable
DELIMITER //
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//
DELIMITER ;
-- CALL ordertotal(20005, 0, @total);
-- SELECT @total;

检查存储过程

SHOW CREATE PROCEDURE ordertotal;  -- 显示用来创建一个存储过程的CREATE语句
SHOW PROCEDURE STATUS;    -- 详细信息
SHOW PROCEDURE STATUS LIKE 'ordertotal';





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值