Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if anything changed in update trigger in t-sql

How can I determine if something has changed in UPDATE trigger? For example I have table named person with only one column NAME which contains value 'Mike'. If I run

UPDATE person SET NAME = 'Mike'  

how can I determine in the update trigger that nothing has changed? I know about UPDATE(col) statement, but I don't want to iterate over columns. Is there any other way to accomplish this?

like image 401
Marian Zagoruiko Avatar asked May 11 '12 11:05

Marian Zagoruiko


People also ask

How do I check if a column is updated in a trigger?

In SQL Server, you can create DML triggers that execute code only when a specific column is updated. The trigger still fires, but you can test whether or not a specific column was updated, and then run code only if that column was updated. You can do this by using the UPDATE() function inside your trigger.

How do I know if a SQL record is updated?

One way is to start a transaction, select the contents of the row and compare it to what you're going to update it to. If they don't match, then do the update and end the transaction. If they match, rollback the transaction.

How can I tell which columns were changed in a SQL Server update?

Using a SQL Server trigger to check if a column is updated, there are two ways this can be done; one is to use the function update(<col name>) and the other is to use columns_updated().

How do you determine if trigger is insert or update or delete?

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.


1 Answers

Update(column) merely states that column participated in update, but not that its value has changed. For instance,

update Person SET Name = Name 

yields true in update(name) even though Name has not been changed in any row.

To check if new values differ from old ones, you would employ except because except will remove rows from top set that exist in bottom set. As person table probably has primary key there is not a danger of removing changed item that has a counterpart in deleted. However if you decide to change * to a list of interesting columns be sure to include primary key.

insert into logTable (ID) select a.ID from (    select * from Inserted    except    select * from Deleted ) a 

Added benefit is that this works for inserts too because Deleted will be empty and all rows from inserted will be returned.

like image 87
Nikola Markovinović Avatar answered Sep 25 '22 10:09

Nikola Markovinović