Click here to Skip to main content
Licence CPOL
First Posted 22 Sep 2006
Views 20,572
Bookmarked 23 times

How to find if only one particular column has been modified in a trigger

By | 6 Oct 2006 | Article
How to find if only one particular column has been modified in a trigger.
 
Part of The SQL Zone sponsored by
See Also

Introduction

Hi people! The following code has been written for SQL Server 2005 Express, and the program running the database has been written in VB.NET 2005.

This SQL code will allow you to know if only one particular column has been modified in a trigger, without having to know the number of columns in the related table.

--Determine if only one column has been 
modified
--@onlyOneColumnUpdated = 0 if not, otherwise @onlyOneColumnUpdated = 1
DECLARE @logForOneColumn float
DECLARE @onlyOneColumnUpdated bit
SET @logForOneColumn = (SELECT (LOG(CONVERT(int,COLUMNS_UPDATED()))/LOG(2)))
SET @onlyOneColumnUpdated = 0
IF CONVERT(int,@logForOneColumn) = @logForOneColumn
    SET @onlyOneColumnUpdated = 1

-- After then you test the column you want to know if it has been modified
IF UPDATE(MyCOlumn) AND @onlyOneColumnUpdated = 1
    -- PUT YOUR CODE HERE FOR THE COLUMN.

The principle is the following:

  • Each table columns has been assigned a multiple of 2. That way, when a column is updated, it is added up to a common number which is always unique. It would not be possible to determine if two columns were modified (it would, but not without knowing the table structure), but we can do for only one.
  • Because CONVERT(int,COLUMNS_UPDATED()) is returning a number, which if the log base 2 gives another integer, then you know that only one column has been modified.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Master DJon

Web Developer

United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralKill performance PinmemberSimon Hughes22:50 25 Sep '06  
GeneralRe: Kill performance PinmemberMaster DJon18:49 28 Sep '06  
GeneralAre you sure this works PinmemberEwout Stortenbeker21:49 25 Sep '06  
GeneralRe: Are you sure this works PinmemberMaster DJon19:03 28 Sep '06  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 6 Oct 2006
Article Copyright 2006 by Master DJon
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid