0

我有两张桌子。一个客户表和一个客户日志表。当任何更新的行在客户中插入或删除时。触发器应该把它的 id 和操作放到日志表中。我的触发器一次只处理一行。谁能告诉我如何满足多个受影响的行场景

ALTER TRIGGER [dbo].[tr_customer_updated] ON [dbo].[Customers]
AFTER UPDATE,INSERT,DELETE
AS 
DECLARE @action as char(10);
DECLARE @customerId as varchar(max);
DECLARE @customerName as varchar(max);
SET @action = 'Inserted'; -- Set Action to Insert by default.
IF EXISTS(SELECT * FROM DELETED)
BEGIN
    SET @action = 
        CASE
            WHEN EXISTS(SELECT * FROM INSERTED) 
            THEN 'Updated' -- Set Action to Updated.
            ELSE 'Deleted' -- Set Action to Deleted.       
        END
        select @customerId = Id, @customerName = Name from DELETED;

END
ELSE 
BEGIN
    IF EXISTS(SELECT * FROM INSERTED) 
    BEGIN
        select @customerId = Id, @customerName = Name from INSERTED;
    END
END
insert into CustomerLogs (CustomerId, CustomerName, ActionPerformed, PerformedOn)
VALUES(@customerId, @customerName, @action, GETDATE())
4

1 回答 1

2

试试这个:

ALTER TRIGGER [dbo].[tr_customer_updated] ON [dbo].[Customers]
AFTER UPDATE,INSERT,DELETE
AS 
DECLARE @action as char(10);
SET @action = 'Inserted'; -- Set Action to Insert by default.
IF EXISTS(SELECT * FROM DELETED)
BEGIN
    SET @action = 
        CASE
            WHEN EXISTS(SELECT * FROM INSERTED) 
            THEN 'Updated' -- Set Action to Updated.
            ELSE 'Deleted' -- Set Action to Deleted.       
        END
        insert into CustomerLogs (CustomerId, CustomerName, ActionPerformed, PerformedOn)
        select Id, Name, @action, GETDATE() from DELETED;

END
ELSE 
BEGIN
    IF EXISTS(SELECT * FROM INSERTED) 
    BEGIN
        insert into CustomerLogs (CustomerId, CustomerName, ActionPerformed, PerformedOn)
        select Id, Name, @action, GETDATE() from INSERTED;
    END
END
于 2013-09-20T17:14:55.107 回答