我有一个正在处理的触发器,当另一个表应用了插入或更新时,它将向表中插入行。到目前为止,Update 部分有效(我最关心的列是 Balance 列),但是当在 Account 表中添加第一行以进行插入时,在我的 AuditTrailCustomerBalance 表中 OldBalance、NewBalance 和 CustNo 设置为 NULL . 如何让 NewBalance 和 CustNo 引用刚刚从触发器插入到表中的值?
这是触发器:
ALTER TRIGGER AuditTrigger
ON Accounts
FOR INSERT, UPDATE
AS
IF UPDATE( Balance )
BEGIN
IF EXISTS
(
SELECT 'True'
FROM Inserted i
JOIN Deleted d
ON i.AccountID = d.AccountID
)
BEGIN
--1. Declare temp variables.
DECLARE @OldBalance NUMERIC( 18, 0 )
DECLARE @NewBalance NUMERIC( 18, 0 )
DECLARE @CustNo INT
--2. Set the variables.
SELECT @OldBalance = Balance FROM deleted
SELECT @NewBalance = Balance FROM inserted
SELECT @CustNo = CustNo FROM inserted
INSERT INTO AuditTrailCustomerBalance( TimeChanged, ChangedBy, OldBalance, NewBalance, CustNo )
VALUES( GETDATE(), SUSER_SNAME(), @OldBalance, @NewBalance, @CustNo )
END
END
GO
和测试语句:
INSERT INTO Custs( CustNo, GivenName, Surname, DOB, SIN )
VALUES( 1, 'Peter', 'Griffen', 'January 15, 1950', '555555555')
INSERT INTO Accounts( CustNo, Type, Balance, AccruedInt, WithdrawalCount )
VALUES( 1, 'Savings', 0, 0, 0 )
UPDATE Accounts SET Balance = 100
WHERE CustNo = 1