Say I have two tables, a “live” table and a history table. The live table looks like this:
CREATE TABLE dbo.LiveTable (
LiveTableId INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
SomeVarChar VARCHAR(20) NOT NULL DEFAULT '',
SomeForeignId INT NULL,
OtherForeingId INT NULL,
ChangeBy VARCHAR(128) NOT NULL,
ChangeTime DATETIME NOT NULL DEFAULT GETDATE()
)
The history table looks the same, except it has its own primary key and an IsDelete column used elsewhere. When a user updates a row in LiveTable, I want to log the row’s prior values in the history table. This is simple enough with an UPDATE trigger, of course. But I’ve just determined that some of my updates aren’t firing the history table insert, and I believe this is due to fields that allow nulls. My trigger looks something like this:
CREATE TRIGGER dbo.trgLiveTableUpdate ON dbo.LiveTable FOR UPDATE
AS
INSERT INTO dbo.LiveTableHistory (
LiveTableId,
SomeVarChar,
SomeForeignId,
OtherForeignId,
ChangeBy,
ChangeTime
)
SELECT
d.LiveTableId,
d.SomeVarChar,
d.SomeForeignId,
d.OtherForeignId,
d.ChangeBy,
d.ChangeTime
FROM DELETED d
JOIN INSERTED i ON d.LiveTableId = i.LiveTableId
WHERE d.SomeVarChar <> i.SomeVarChar
OR d.SomeForeignId <> i.SomeForeignId //<--- I don't think this works
OR d.OtherForeignId <> i.OtherForeignId //<--- this either
Is it possible that my WHERE condition isn’t hitting on situations where the change is to SomeForeignId or OtherForeignId because those columns both allow nulls? If so, how would I write a condition that would take nulls into account when checking those columns for inequality?
You could also find the EXCEPTions, which give you the keys to record.