我正在创建两个触发器。一个用于捕获Rewards表的插入值,另一个用于捕获Rewards表的已删除值。触发器主要功能是记录对审计表进行的更改类型。
奖励表: enter image description here
审核表: enter image description here
audit_insert_trigger的SQL是:
CREATE TRIGGER tr_rewards_insert
ON Rewards AFTER INSERT, UPDATE
AS IF UPDATE(category)
BEGIN
DECLARE @category char(6)
DECLARE @type_change char(20)
SELECT @category = (SELECT category FROM inserted)
IF EXISTS (SELECT * FROM inserted)
BEGIN
SELECT @type_change = 'Inserted'
END
INSERT INTO audit_rewards
VALUES (
@category, USER_NAME(), GETDATE(), @type_change)
END
CREATE TRIGGER tr_rewards_delete
ON Rewards AFTER UPDATE
AS IF UPDATE(category)
BEGIN
DECLARE @category char(6)
DECLARE @type_change char(20)
SELECT @category = (SELECT category FROM deleted)
IF EXISTS (SELECT * FROM deleted)
BEGIN
SELECT @type_change = 'Deleted'
END
INSERT INTO audit_rewards
VALUES (
@category, USER_NAME(), GETDATE(), @type_change)
END
我的想法是只更换“插入”的位置并将其“删除”。我不是真正理解1.关于为什么不起作用的逻辑2.如何将删除的值放入审计表并记录它是删除。
无法在一个触发器中进行。必须是两个独立的触发器。
答案 0 :(得分:0)
您的insert
触发器不正确。我认为应该是:
CREATE TRIGGER tr_rewards_insert
ON Rewards AFTER INSERT, UPDATE
AS IF UPDATE(category)
BEGIN
INSERT INTO audit_rewards
SELECT 'INSERTED, USER_NAME(), GETDATE(), category
FROM inserted;
END;
DELETED
触发器基本上是相同的。绝不假设inserted
和deleted
只有一行。
答案 1 :(得分:0)
找出答案:
CREATE TRIGGER tr_rewards_insert
ON Rewards AFTER INSERT, UPDATE
AS IF UPDATE(category)
BEGIN
DECLARE @category char(2)
DECLARE @type_change char(20)
SELECT @category = (SELECT category FROM inserted)
SELECT @type_change = 'Inserted'
INSERT INTO audit_rewards
VALUES (@category, USER_NAME(), GETDATE(), @type_change)
END
CREATE TRIGGER tr_rewards_delete
ON Rewards AFTER DELETE, UPDATE
AS IF UPDATE(category)
BEGIN
DECLARE @category char(2)
DECLARE @type_change char(20)
SELECT @category = (SELECT category FROM deleted)
SELECT @type_change =
INSERT INTO audit_rewards
VALUES (@category, USER_NAME(), GETDATE(), @type_change)
END