SQL Server触发器:当另一个表的列值增加时,如何增加表中的列值?
问题描述:
表组件:SQL Server触发器:当另一个表的列值增加时,如何增加表中的列值?
表材料:
我怎么能写一个触发器在material
表以降低material_quantity
值时component_quantity
是否增加?
顺便说一下,组件是由材料制成的,所以当一个组件的数量增加时,具有相同数量material_id
的材料数量将会以相同的数量减少。
答
插入/更新触发器应该可以帮到你。
CREATE TRIGGER some_name
ON dbo.components
AFTER INSERT, UPDATE
AS
BEGIN
UPDATE m
SET material_quantity = m.material_quantity - (i.component_quantity - c.component_quantity)
FROM materials m
INNER JOIN components c ON c.material_id = m.material_id
INNER JOIN inserted i ON c.component_id = i.component_id
END
只需发出UPDATE命令。 –