1、商品表修改语句添加触发器,要求在修改商品售价时不允许上下浮动超过10%。
BEGINDECLARE old_price DECIMAL(10,2);DECLARE new_price DECIMAL(10,2);DECLARE price_change DECIMAL(10,2);-- 获取新旧价格SET old_price = OLD.price;SET new_price = NEW.price;-- 计算价格变化百分比IF (new_price <> 0) THENSET price_change = (new_price - old_price) / old_price * 100;ELSE-- 如果新价格为0,则不允许更新SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '新价格不能为0。';END IF;-- 检查价格变动是否超过10%IF (price_change > 10 OR price_change < -10) THENSIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '商品售价上下浮动不能超过10%。';END IF;
END;
测试语句
-- 插入测试数据:
insert into dishes(`name`,price,stock_quantity) VALUES ( '大鱼头',55.00,100);
-- 正常更新(未超10%)
UPDATE dishes set price =8.00 WHERE `name`='大鱼头'; -- 触发错误
2.订单表删除语句添加触发器,要求在删除订单信息时先删除订单详情表中的订单信息。
$$
DELIMITER ;
DELIMITER //
CREATE TRIGGER trg_cascade_delete_order_items
AFTER DELETE ON orders
FOR EACH ROW
BEGINDELETE FROM order_items WHERE order_id = OLD.id;
END;
//
DELIMITER ;
测试语句
DELETE FROM `order` WHERE `order_id` = 刚才添加的id号;
存储过程
这个存储过程create_order_infos用于在数据库中创建一个新的订单,并更新相关详情
DELIMITER //CREATE PROCEDURE create_order_infos(IN in_user_id INT,IN in_dish_id INT,IN in_quantity INT
)
BEGIN-- 注释:声明变量用于存储相关信息DECLARE dish_price DECIMAL(10, 2);DECLARE total_price DECIMAL(10, 2);DECLARE order_id INT;DECLARE restaurant_id INT;-- 注释:获取菜品价格SELECT price INTO dish_price FROM dishes WHERE id = in_dish_id;-- 注释:计算订单总价SET total_price = dish_price * in_quantity;-- 注释:获取菜品所属餐厅 IDSELECT restaurant_id INTO restaurant_id FROM dishes WHERE id = in_dish_id;-- 注释:插入订单信息到订单表INSERT INTO orders (user_id, restaurant_id, order_date, total_price, status)VALUES (in_user_id, restaurant_id, NOW(), total_price, '待支付');-- 注释:获取生成的订单 IDSET order_id = LAST_INSERT_ID();-- 注释:插入订单详情信息到订单详情表INSERT INTO order_items (order_id, dish_id, quantity, price_per_item)VALUES (order_id, in_dish_id, in_quantity, dish_price);-- 注释:更新商品表的库存数量UPDATE dishes SET stock_quantity = stock_quantity - in_quantity WHERE id = in_dish_id;END //
测试语句
DELIMITER ;
CALL create_order_infos(2, 3, 2);