我有一个表PeroidicDeduction,字段是ID(自动递增),TotalDeduction(例如可以贷款),付费(每月扣除),RemainingAmount,
我想要的是每当我插入或更新表时--- RemainingAmount将获得TotalDeduction-SUM(付费)....的值并编写以下触发器...但是对我不起作用
创建TRIGGER dbo.UpdatePD ON PeroidicDedcution 插入后,更新
AS
BEGIN
更新PeroidicDedcution SET REmaininAmoubnt =(SELECT TotalDeduction-(SELECT SUM(付费)FROM PeroidicDeduction)FROM PeroidicDeduction)
END
注意:它位于单个表
上答案 0 :(得分:2)
创建两个触发器,一个INSTEAD OF UPDATE和INSTEAD OF INSERT。以下是INSTEAD OF UPDATE的代码:
CREATE TRIGGER dbo.UpdatePD ON PeroidicDedcution
INSTEAD OF Update
AS
SET NOCOUNT ON
UPDATE p
SET col1=i.col1
,col2=i.col2
FROM INSERTED i
INNER JOIN PeroidicDedcution p ON i.PK=p.PK
UPDATE PeroidicDedcution
SET REmaininAmoubnt=(SELECT TotalDeduction-(SELECT SUM(Paid) FROM PeroidicDeduction) FROM PeroidicDeduction)
go
它将执行触发触发器的原始更新,以及问题中触发器的SUM逻辑。
这是INSTEAD OF INSERT触发器:
CREATE TRIGGER dbo.InsertPD ON PeroidicDedcution
INSTEAD OF INSERT
AS
SET NOCOUNT ON
INSERT INTO PeroidicDedcution
(col1, col2, ...)
SELECT
col1, col2, ...
FROM INSERTED
UPDATE PeroidicDedcution
SET REmaininAmoubnt=(SELECT TotalDeduction-(SELECT SUM(Paid) FROM PeroidicDeduction) FROM PeroidicDeduction)
go
答案 1 :(得分:1)
您不应该使用触发器来执行此操作,因为如果您在表上有更新触发器并且触发器导致并更新到同一个表,它将以递归方式触发自身。而是将逻辑添加到插入并更新存储过程