SQL Server ON DELETE触发器无法按预期工作

时间:2019-06-07 17:36:57

标签: sql-server triggers

我正在尝试在数据库中创建触发器。

我有两个表,一个用于客户信息,一个用于客户订单。 我想创建一个FOR DELETE触发器,以便在从订单表中删除订单时,应该从客户帐户中减少该订单的费用。

首先,我创建一个AFTER INSERT触发器,效果很好!

代码如下:

ALTER TRIGGER [dbo].[set_customer_debt]
ON [dbo].[orders]
AFTER INSERT
AS 
BEGIN
    UPDATE customer
    SET debt = debt + (SELECT cost FROM orders
                       INNER JOIN services ON services.service# = orders.service#
                       WHERE orders.order# IN (SELECT order# FROM inserted))
    WHERE customer# IN (SELECT customer# FROM inserted)
END

然后,我将其复制并更改为FOR DELETE,但对于债务它只返回NULL:

ALTER TRIGGER [dbo].[delete_customer_debt]
ON [dbo].[orders]
FOR DELETE
AS 
BEGIN
    UPDATE customer
    SET debt = debt - (SELECT cost FROM orders
                       INNER JOIN services ON services.service# = orders.service#
                       WHERE orders.order# IN (SELECT order# FROM deleted))
    WHERE customer# IN (SELECT customer# FROM deleted)
END

问题出在哪里?

0 个答案:

没有答案