Microsoft SQL Server 2012 Bible
by Adam Jorgensen, Jorge Segarra, Patrick LeBlanc, Jose Chinchilla, Aaron Nelson
Working with the Transaction
SQL Server provides several ways for the trigger to determine the effects of the DML statement. The first two methods are the UPDATE() and columns_updated() functions, which are used to determine which columns were potentially affected by the DML statement. The other methods use deleted and inserted images, which contain the before and after data sets.
Determining the Updated Columns
SQL Server provides the UPDATE() function to test if a single column is affected by the DML transaction:
IF UPDATE(ColumnName)
Because an INSERT affects all columns, the UPDATE() function returns true for any column you pass. Conversely, UPDATE()always returns false for a DELETE. The following example demonstrates the UPDATE() function:
ALTER TRIGGER HumanResources.TriggerOne ON HumanResources.Department AFTER INSERT, UPDATE AS IF Update(GroupName) BEGIN; PRINT ‘You might have modified the GroupName column'; END; ELSE BEGIN; PRINT ‘The GroupName column is untouched.'; END;
With the trigger looking for changes to the LastName column, the following DML statement tests the trigger:
UPDATE HumanResources.Department SET GroupName = ‘Forecasting & Analytics ' WHERE Name = 'Data Management';
Result:
You might have modified the GroupName column
Note that the UPDATE() function returns true even if the column is updated with the same value, for example, from ‘abc' to ‘abc'.
The columns_updated() function returns a bitmapped varbinary data type representation of the columns updated. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access