I have this trigger which works functionally (as far as I can tell by my tests) but I strongly suspect I can simplify the code by using IF UPDATE… I just don’t fully understand how it works. I seem to do best undestanding triggers in terms of the inserted and deleted tables.
Can this trigger be simplified in the way I just mentioned (or any other way that improves the readability)?
CREATE TRIGGER [dbo].[tr_Affiliate_IU]
ON [dbo].[Affiliate]
AFTER INSERT, UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Get the current date.
DECLARE @getDate DATETIME = GETDATE()
-- Set the initial values of date_created and date_modified.
UPDATE
dbo.Affiliate
SET
date_created = @getDate
FROM
dbo.Affiliate A
INNER JOIN INSERTED I ON A.id = I.id
LEFT OUTER JOIN DELETED D ON I.id = D.id
WHERE
D.id IS NULL
-- Ensure the value of date_created does never changes.
-- Update the value of date_modified to the current date.
UPDATE
dbo.Affiliate
SET
date_created = D.date_created
,date_modified = @getDate
FROM
dbo.Affiliate A
INNER JOIN INSERTED I ON A.id = I.id
INNER JOIN DELETED D ON I.id = D.id
END
If updated(column_name) cannot help as it merely states that column participated in a query that raised the trigger. The update part of the trigger can be shortened by use of case statement to help decide which date date_created is going to hold.