SQL Server触发器:当另一个表的列值增加时,如何增加表中的列值?

问题描述:

表组件:SQL Server触发器:当另一个表的列值增加时,如何增加表中的列值?

enter image description here

表材料:

enter image description here

我怎么能写一个触发器在material表以降低material_quantity值时component_quantity是否增加?

顺便说一下,组件是由材料制成的,所以当一个组件的数量增加时,具有相同数量material_id的材料数量将会以相同的数量减少。

+0

只需发出UPDATE命令。 –

插入/更新触发器应该可以帮到你。

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 
+0

当发生UPDATE时,您的代码不会考虑'deleted'中的任何值,即计算更新所产生的增量。我想知道OP可能需要什么。 – HABO

+0

@HABO是的,也想到了它。但更好地使用另一个删除触发器。并且应该有外键,因此删除可能不会很顺利 – gofr1