1

我有两个表,分别称为Table_ATable_B。我想创建一个触发器,以便每当更新Table_Apayment中的字段时,应将一条新记录插入到Table_B中,以显示之前的总付款额和现在的总付款额之间的差异。两张表如下:

表_A

A_id | payment |
 1   |  1000   |
 2   |   200   |

表_B

B_id |  difference |

我的触发器实现如下。我不确定如何计算这种差异:

CREATE TRIGGER trigger_Difference
ON Table_A
FOR UPDATE
AS
BEGIN
 DECLARE @Difference as INT
 DECLARE @PreviousDiff as INT

 BEGIN
    SELECT @PreviousDiff = SUM(payment)
    FROM Table_A
 END

 if update(payment)
    BEGIN
        SELECT @Difference = ***don't know what to put here*** 
        FROM inserted

        INSERT INTO Table_B (difference) VALUES (@Difference)
    END
END
4

1 回答 1

1

这个问题的另一个解决方案是在存储过程中使用 OUTPUT 子句来进行更新,或者只是根据您的需要调整此方法。

IF OBJECT_ID('TABLE_A') IS NOT NULL DROP TABLE TABLE_A
IF OBJECT_ID('TABLE_B') IS NOT NULL DROP TABLE TABLE_B
IF OBJECT_ID('sp_Payment_Update') IS NOT NULL DROP PROC sp_Payment_Update
GO

CREATE TABLE TABLE_A (
    A_ID INT IDENTITY(1,1),
    Payment INT
)

CREATE TABLE TABLE_B (
    B_ID INT ,
    OldPayment INT,
    NewPayment INT
)
GO

INSERT INTO TABLE_A VALUES (1000),(1200)
GO

CREATE PROC sp_Payment_Update
    @A_ID INT,
    @Payment INT
AS BEGIN

    UPDATE TABLE_A
    SET Payment = @Payment
        OUTPUT
            INSERTED.A_ID,
            DELETED.Payment,
            INSERTED.Payment
        INTO TABLE_B
    WHERE A_ID = @A_ID


    SELECT * FROM TABLE_A
    SELECT * FROM TABLE_B
END
GO

EXEC sp_Payment_Update 1, 1500

更新代码本身将在 TABLE_B 中记录您使用它所做的许多更改,您也可以在TABLE_B放置一个 UpdateDate 列,默认值为GETDATE()以使其提供更多信息。

于 2014-10-27T07:43:48.593 回答