sql-server-2012 - 根据父表条件触发更新
问题描述
嗨,我使用 SQL SERVER 2012,我有两个名为 tbcustomer 和 tbcustomerdetail 的表。两个表都有列 customerID。
我只管理 tbcustomerdetail。如果我更新 tbcustomerdetail where customerID='001' 那么我需要触发器来更新 tbcustomer where customerID='001'
我试试这个,但没有找到拼写。
CREATE TRIGGER Deletecustomer
ON tbcustomerdetail
FOR UPDATE
AS
BEGIN
update tbcustomer tbcustomer.status=0 where tbcustomer.customerID=updated.customerID;
END
//updated.customerID is the ID on column tbcustomerdetail where customerID is '001'.
我也试过更新后但它不起作用。
解决方案
Updated
不存在,在触发器中,您有两个视图Deleted
,其中包含以前的数据并Inserted
包含新的数据
正如我提到的,它们是视图,包含受语句影响的所有行的数据,因此,您需要在连接中使用它们
CREATE TRIGGER Deletecustomer
ON tbcustomerdetail
FOR UPDATE
AS
BEGIN
UPDATE C
SET Status = 0
FROM tbCustomer C
JOIN Inserted I ON C.CustomerID = I.CustomerID
END