存储过程创建

1、添加一个用户下订单的存储过程

-- 存储过程
DELIMITER $$
CREATE PROCEDURE create_order_infos(
    IN user_id_param INT,
    IN product_id_param INT,
    IN quantity_param INT,
    OUT order_id_out INT
)
BEGIN

    DECLARE product_price DECIMAL(10, 2);
    DECLARE total_cost DECIMAL(10, 2);
    DECLARE user_balance DECIMAL(10, 2);
    DECLARE wallet_log_id INT;
 
    SELECT price INTO product_price FROM product WHERE product_id = product_id_param;
 
    SET total_cost = product_price * quantity_param;
 
    SELECT balance INTO user_balance FROM user_wallet WHERE user_id = user_id_param;
 
    IF user_balance < total_cost THEN
      
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '用户余额不足,无法完成订单。';
    ELSE
        
        START TRANSACTION;
 
        INSERT INTO user_wallet_log (user_id, transaction_type, amount, transaction_time)
        VALUES (user_id_param, '支出', total_cost, NOW());
        SET wallet_log_id = LAST_INSERT_ID();
 
        UPDATE user_wallet SET balance = balance - total_cost WHERE user_id = user_id_param;
 
        INSERT INTO `order` (user_id, order_status, total_price)
        VALUES (user_id_param, '待支付', total_cost);
        SET order_id_out = LAST_INSERT_ID();
 
        INSERT INTO order_info (order_id, product_id, quantity, unit_price)
        VALUES (order_id_out, product_id_param, quantity_param, product_price);
 
        COMMIT;
    END IF;
END $$
DELIMITER ;

2、测试存储过程1:买不起效果

-- 测试存储过程1
 
-- 假设我们有一个用户和一个商品,它们的ID分别为6和6,我们要购买数量为2的商品
SET @user_id = 6;
SET @product_id = 6;
SET @quantity = 2;
SET @order_id = NULL;
 
 
-- 调用存储过程
CALL create_order_infos(@user_id, @product_id, @quantity, @order_id);
 
 
-- 查询返回的订单ID
SELECT @order_id;

 

3、测试存储过程2:买得起的效果 

--  测试存储过程2
SET @user_id = 2;
SET @product_id = 11;
SET @quantity = 1;
SET @order_id = NULL;
 
 
-- 调用存储过程
CALL create_order_infos(@user_id, @product_id, @quantity, @order_id);
 
 
-- 查询返回的订单ID
SELECT @order_id;

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值