我有三个表,购买(purchase_id,quantity_purchased,purchase_date,purchase_time,payment_method)库存(inventory_id,amount,item_id)和商品(item_name,price,notes,item_id)我需要创建一个触发器来更新库存(每次进行新购买时,金额 - 数量 - 购买量。这就是我到目前为止所做的:
CREATE TRIGGER inventory_update
AFTER INSERT ON purchases
FOR EACH ROW
UPDATE inventory
SET amount = amount - NEW.quantity_purchased
WHERE purchase_id = NEW.purchase_id;
感谢任何帮助,谢谢
答案 0 :(得分:0)
是否有将您的购买表与您的广告资源相关联的外键?
以下是我的头脑风暴,如果您可以确定在插入产品表时销售的产品,它应该可以使用。
Create trigger inventory_update on Dbo.purchases
after insert
as
declare @inserted int, @stock int, @pid int
select @Pid= pid from inserted
select @inserted = quantity_purchased from inserted
select @stock = quantity_purchased from dbo.inventory
where @PID= inventory. inventory_id -- This line needs a way to find out what the purchase item is
if @inserted>@stock
begin
print('Not enough Stock')
rollback
end
Else if @inserted<@stock and @PID is not null
begin
update inventory
set amount= inventory.amount-@inserted
where @PID =inventory.item_ID -- Once again the issue is figuring out what your purchase item is on this line.
print('A Sale has been made')
end
else
print('There is an error in the process')
答案 1 :(得分:0)
我猜我purchases
表有一个item_id
。如果是这样的话:
DELIMITER $$
CREATE TRIGGER inventory_update AFTER INSERT ON purchases
FOR EACH ROW
BEGIN
UPDATE inventory i
SET i.amount = i.amount - NEW.quantity_purchased
WHERE i.item_id = NEW.item_id;
END;
$$
DELIMITER ;