Wednesday, September 16, 2015

SQL Server triggers, how to only log rows where values have actually changed.

In SQL Server inside a trigger if you want to check if a row has actually changed, you would think you could use COLUMNS_UPDATED but this only returns which columns are included in an update statement. It doesn't check if the actual values changed. A nice solution I've found is to make use of the SQL EXCEPT operator and a CTE. Here's a sample that you may find useful.


 ...  
 FOR UPDATE  
 AS  
 declare @rijen int  
 ;with ChangedData as   
      (  
      select deleted.column1, deleted.column2, deleted.column3, deleted.column4 from deleted  
           except  
      select inserted.column1, inserted.column2, inserted.column3, inserted.column4 rom inserted  
      )  
 select @rijen = count(*) from ChangedData  
 if @rijen > 0  
 begin  
 ...  
 end  

No comments:

Post a Comment