I'm a newbie to SQL and I have to write a trigger that checks if there is enough product stock for new orders. Also if the order quantity is greater than a certain number I need to update the discount row.
But apparently you are not allowed to update a table from an INSERT trigger. How do I go about doing this?
This is what I've written so far
DELIMITER //
create trigger before_order before insert on order_detail FOR EACH ROW
BEGIN
declare stock_remain int;
declare ord_quantity int;
declare inventory int;
declare price int;
declare p_id int;
declare ord_id int;
select product_id into @p_id from order_detail where product_id = new.product_id;
select unit_price into @price from order_detail where unit_price = new.unit_price;
select order_detail_id into @ord_id from order_detail where order_detail_id = new.order_detail_id;
SET @stock_remain=est_remaining_stock(@price, @p_id);
select quantity into @ord_quantity from order_detail where order_detail_id=@ord_id;
SET @inventory = @stock_remain - @ord_quantity;
IF @inventory < 10 THEN
signal sqlstate '45001' set message_text = "No way ! You cannot do this !";
END IF;
IF @ord_quantity > 40 THEN
UPDATE order_detail SET new.discount = 5 where product_id=new.product_id;
END IF;
END;
//
DELIMITER ;