December 5, 2012 at 3:00 am
hi Team,
I want to create a trigger, that that should fire when ever particular columns are updated/inserted.
am using below query.. is it correct way.
CREATE TRIGGER [TRG_TESTING]
ON TABLE_NAME
AFTER INSERT,UPDATE
AS
SET NOCOUNT ON
IF (UPDATE (Col1,Col2,Col3) OR
(INSERT (Col1,Col2,Col3)
DECLARE
@Var1 varchar(max),
@ID INT
---
---
--
.
December 5, 2012 at 3:34 am
Look at the COLUMNS_UPDATED() clause
http://msdn.microsoft.com/en-us/library/765fde44-1f95-4015-80a4-45388f18a42c
December 5, 2012 at 7:06 am
UPDATE takes only one column. There is no similar 'INSERT' function; UPDATE checks for both.
Your line would change to
IF (UPDATE(Col1) OR UPDATE(Col2) OR UPDATE(Col3))
You could also use COLUMNS_UPDATED, but that may be confusing with the bit mask.
Edit: removed quote
______________________________________________________________________________
How I want a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.
December 5, 2012 at 7:12 am
I think your trigger model needs to look more like this.
because triggers handle multiple rows in SQL server, you should never declare a variable in a trigger, because it makes you think of one row/one value, instead of the set.
there are exceptions of course, but it's a very good rule of thumb.
also note the UPDATE function doesn't tell you the VALUE changed on a column...only whether the column was included int eh column list for insert/update. so if it was updated to the exisitng value (and a lot of data layers will do that automatically) it's a false detection of a change.
CREATE TRIGGER [TRG_TESTING]
ON TABLE_NAME
AFTER INSERT,UPDATE
AS
SET NOCOUNT ON
INSERT INTO SomeTrackingTable(ColumnList)
SELECT ColumnList
FROM INSERTED
LEFT OUTER JOIN DELETED
ON INSERTED.SomePrimaryKey = DELETED.SomePrimaryKey
WHERE DELETED.SomePrimaryKey IS NULL --inserted only
OR (INSERTED.SpecificColumn <> DELETED.SpecificColumn) --this column changed...so we need to log it.
Lowell
December 6, 2012 at 6:50 am
This can be found in BOL:
1) IF UPDATE(b) OR UPDATE(c) ...
2) IF ( COLUMNS_UPDATED() & 2 = 2 )
Best,
Kevin G. Boles
SQL Server Consultant
SQL MVP 2007-2012
TheSQLGuru on googles mail service
Viewing 5 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy