Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

trigger refresher

Status
Not open for further replies.

Bell1991

Programmer
Aug 20, 2003
386
US
How do i create a trigger for update. I need it to update the modified date and how it was updated based on the id that was just updated..

It has been a while since i worked with triggers..

Create TRIGGER tblUpdate on tblA
For Update
As
Update tblA
set dtDateModified = getDate() ,
FlagHowModified = 'web'
where ID = (ID just updated)

Thanks
 
You would use the ID from the Inserted table.


Code:
Create TRIGGER tblUpdate on tblA
For Update
As
Update tblA
    set dtDateModified = getDate() ,
         FlagHowModified = 'web'
FROM tblA A
 JOIN INSERTED 
  ON i.ID = A.id

- Paul
10qkyfp.gif

- If at first you don't succeed, find out if the loser gets anything.
 
I would add to the condition

instead of

JOIN INSERTED
ON i.ID = A.id

I would do

JOIN INSERTED
ON i.ID = A.id
and i.SomeCole <> a.Somecol

because the trigger will fire even if you do this


update table set
val = val
where id = 1

see nothing got changed but the trigger will still fire

and also beware of nulls
you have to use cloalese around this becuase if you change from or to nulls it won't match

read this (


Denis The SQL Menace
--------------------
SQL Server Code,Tips and Tricks, Performance Tuning
SQLBlog.com
Google Interview Questions
 
Hey, and as long as we're at it (FAQ in the making?):

Code:
-- make sure we use the correct database:
USE TheRightDatabase
GO

-- drop the trigger if it exists:
IF OBJECT_ID ('trg_UpdateStatistics_U','TR') IS NOT NULL
   DROP TRIGGER trg_UpdateStatistics_U
GO

-- build the new and improved (?) trigger:
CREATE TRIGGER trg_UpdateStatistics_U
    ON dbo.StatisticalStuffWeTrack
   FOR UPDATE
AS...

< M!ke >
Acupuncture: a jab well done.
 
But where should the if@@ be? [I'm new to SQL and try to
get a trigger working. 1st checking what's here :) ]
-- 8< ------------ 8< --------- 8< ---------
-- make sure we use the correct database:
USE TheRightDatabase
GO

-- drop the trigger if it exists:
IF OBJECT_ID ('tblUpdate','TR') IS NOT NULL
DROP TRIGGER tblUpdate
GO

-- build the new and improved (?) trigger:
Create TRIGGER tblUpdate on tblA
For Update
As
if @@rowcount =0
return
Update tblA
set dtDateModified = getDate() ,
FlagHowModified = 'web'
FROM tblA A
JOIN INSERTED
ON i.ID = A.ID
AND i.SomeCol <> a.Somecol
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top