Monday, February 27, 2012

Help me write my first Update Trigger (sql svr 2000)

can someone help me write a Trigger? I have never written a trigger. This is for SQL Server 2000

Table FOO:
----
ID (numberic counter)
Status (Char)
etc..

Table BAR:
----
ID
Status
DateUpdated (getdate())

Whenever the Status in Table FOO is updated, I need to INSERT a new record into BAR with the ID and Status

~LeCREATE TRIGGER FOO_Update ON [FOO]
FOR Insert, Update
AS
Insert into Bar
(ID,
Status,
DateUpdated)
Select ID,
Status,
Getdate()
From inserted

...but you should really think of just adding the DateUpdated field to FOO with a default of getdate() for new records and having the trigger update it:

CREATE TRIGGER FOO_Update ON [FOO]
FOR Update
AS
Update FOO
set DateUpdated = Getdate()
From FOO
inner join inserted on FOO.ID = inserted.ID

blindman|||B.E.A.U.-tiful

Works Perfectly!

Thank you very very much!

~Le

No comments:

Post a Comment