Question : sql trigger - compare new and old value after update

How do i compare new and old value in a trigger after update?
if update() is no good because i want to know if the value is changed and not if the column was updated.

Keren

Answer : sql trigger - compare new and old value after update

You can use the temporary inserted and deleted tables inside your trigger.

An update transaction is similar to a delete operation followed by an insert operation; the old rows are copied to the deleted table first, and then the new rows are copied to the trigger table and to the inserted table. This means that you can compare a column from the deleted table with a column from the inserted table. Remember to also include a unique key for the record in the comparison since both the deleted and inserted table may consist of several rows.

Example:

I have a table called 'table1' with a unique ID field (in my case an identity field), a varchar(50) name field and an integer field called namechanged which tracks how many times the name has been changed.

CREATE TRIGGER [table1_update] ON [dbo].[Table1]
FOR  UPDATE
AS begin
  update table1 set table1.namechanged = table1.namechanged + 1
  from inserted i, deleted d
  where i.[name] <> d.[name] and i.[id] = d.[id] and table1.[id] = i.[id]
end

The namechanged field now only increments when the name field actually changes.
Random Solutions  
 
programming4us programming4us