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())
答案 0 :(得分: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
答案 1 :(得分:1)
更简单的解决方案:
-- This statement uses following assumptions:
-- 1) customerID can't be changed (IDENTITY) or isn't changed
-- 2) customerID is mandatory (NOT NULL)
-- 3) it can't detect MERGE statements
INSERT INTO ...
SELECT [action] =
CASE
WHEN i.customerID IS NOT NULL AND d.customerID IS NULL THEN 'insert'
WHEN i.customerID IS NOT NULL AND d.customerID IS NOT NULL THEN 'update'
WHEN i.customerID IS NULL AND d.customerID IS NOT NULL THEN 'delete'
END,
customerID = ISNULL(d.customerID, i.customerID),
customerName = ISNULL(d.customerName, i.customerName)
FROM inserted i
FULL OUTER JOIN deleted d ON i.customerID = d.customerID;