Insert Update trigger how to determine if insert or update
Triggers have special INSERTED
and DELETED
tables to track "before" and "after" data. So you can use something like IF EXISTS (SELECT * FROM DELETED)
to detect an update. You only have rows in DELETED
on update, but there are always rows in INSERTED
.
Look for "inserted" in CREATE TRIGGER.
Edit, 23 Nov 2011
After comment, this answer is only for INSERTED
and UPDATED
triggers.
Obviously, DELETE triggers can not have "always rows in INSERTED
" as I said above
CREATE TRIGGER dbo.TableName_IUD
ON dbo.TableName
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON;
--
-- Check if this is an INSERT, UPDATE or DELETE Action.
--
DECLARE @action as char(1);
SET @action = 'I'; -- Set Action to Insert by default.
IF EXISTS(SELECT * FROM DELETED)
BEGIN
SET @action =
CASE
WHEN EXISTS(SELECT * FROM INSERTED) THEN 'U' -- Set Action to Updated.
ELSE 'D' -- Set Action to Deleted.
END
END
ELSE
IF NOT EXISTS(SELECT * FROM INSERTED) RETURN; -- Nothing updated or inserted.
...
END