snippetsqlMinor
In a trigger, how to check if no fields have changed?
Viewed 0 times
triggerfieldshowcheckchangedhave
Problem
If we receive an update statement that does not check if the value has changed in the where clause, what are the different ways to ignore that update inside a trigger?
I know we can do a comparison of each individual field (handling the ISNULL side as well), but where it's a table that has 50+ fields, is there a faster/easier way to do it?
Note: This could be used to reduce IO/noise in audit records etc...
EXAMPLE
For a table of:
with an after updater trigger containing:
with initial values:
Now run an update:
I know we can do a comparison of each individual field (handling the ISNULL side as well), but where it's a table that has 50+ fields, is there a faster/easier way to do it?
Note: This could be used to reduce IO/noise in audit records etc...
EXAMPLE
For a table of:
CREATE TABLE myTest
(ID int NOT NULL IDENTITY(1,1),
Field1 varchar(10) NULL,
Field2 varchar(20) NULL)with an after updater trigger containing:
INSERT INTO myTestAudit (ID, Field1, Field2, DateTimeUpdate)
SELECT ID, Field1, Field2, getDate()
FROM insertedwith initial values:
INSERT INTO myTest (Field1, Field2)
SELECT 'a', 'b' UNION ALL
SELECT 'a', 'c'Now run an update:
UPDATE myTest set Field2 = 'b' WHERE Field1 = 'a'Solution
To bring back rows where at least one value has changed you can use
SELECT /*TODO: Column List*/
FROM INSERTED I
JOIN DELETED D
ON I.ID = D.ID
AND EXISTS (SELECT I.*
EXCEPT
SELECT D.*)Code Snippets
SELECT /*TODO: Column List*/
FROM INSERTED I
JOIN DELETED D
ON I.ID = D.ID
AND EXISTS (SELECT I.*
EXCEPT
SELECT D.*)Context
StackExchange Database Administrators Q#11896, answer score: 5
Revisions (0)
No revisions yet.