1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| DELIMITER // CREATE PROCEDURE ProcessOrder( IN p_user_id INT, IN p_product_id INT, IN p_quantity INT, OUT p_order_id INT, OUT p_result_code INT, OUT p_result_message VARCHAR(255) ) BEGIN DECLARE v_stock_quantity INT DEFAULT 0; DECLARE v_product_price DECIMAL(10,2) DEFAULT 0; DECLARE v_user_balance DECIMAL(10,2) DEFAULT 0; DECLARE v_total_amount DECIMAL(10,2) DEFAULT 0; DECLARE v_error_count INT DEFAULT 0; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; SET p_result_code = -1; SET p_result_message = '订单处理失败:数据库异常'; END; START TRANSACTION; SELECT stock_quantity, price INTO v_stock_quantity, v_product_price FROM products WHERE id = p_product_id AND status = 1 FOR UPDATE; IF v_stock_quantity < p_quantity THEN SET p_result_code = 1001; SET p_result_message = CONCAT('库存不足,当前库存:', v_stock_quantity); ROLLBACK; ELSE SELECT balance INTO v_user_balance FROM user_accounts WHERE user_id = p_user_id FOR UPDATE; SET v_total_amount = v_product_price * p_quantity; IF v_user_balance < v_total_amount THEN SET p_result_code = 1002; SET p_result_message = CONCAT('余额不足,需要:', v_total_amount, ',当前余额:', v_user_balance); ROLLBACK; ELSE INSERT INTO orders (user_id, product_id, quantity, unit_price, total_amount, status, created_at) VALUES (p_user_id, p_product_id, p_quantity, v_product_price, v_total_amount, 1, NOW()); SET p_order_id = LAST_INSERT_ID(); UPDATE products SET stock_quantity = stock_quantity - p_quantity, updated_at = NOW() WHERE id = p_product_id; UPDATE user_accounts SET balance = balance - v_total_amount, updated_at = NOW() WHERE user_id = p_user_id; INSERT INTO account_transactions (user_id, order_id, amount, type, description, created_at) VALUES (p_user_id, p_order_id, -v_total_amount, 'purchase', '购买商品', NOW()); COMMIT; SET p_result_code = 0; SET p_result_message = '订单处理成功'; END IF; END IF; END // DELIMITER ;
CALL ProcessOrder(1001, 2001, 2, @order_id, @result_code, @result_msg); SELECT @order_id as '订单ID', @result_code as '结果码', @result_msg as '结果信息';
|