Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
DEBBIECOATES
Starting Member
1 Post |
Posted - 2007-10-22 : 13:38:51
|
I have 3 tables on my db, Projects, ProljectAllocationLog and UsersProject consists of Projectid(PK), ProjectName, UserIDProjectAllocationLog consists of ProjectAllocationID(PK), Projectid, UserID,DateUsers consists of UserID (PK), FullnameOver the course of time the user allocated to a project may change. The db has been set up to always show the most current user in the UserID of the Projects table, I want to create a log that will record everytime that user has changed. (ProjectAllocationLog)Having read through some examples posted on Forums, I believe that I can do this with a trigger, but I am not sure if I am doing it right, the trigger I have written isCreate Trigger tr_UpdateAllocationLogON ProjectsAFTER UpdateASIf NOT UPDATE (Userid) DECLARE @PROJECTID DECLARE @NEWUSER DECLARE @PREVIOUSUSERSET @PROJECTID= (SELECT projected FROM Inserted)SET @NEWUSER = (SELECT UserID from Inserted)SET @ PREVIOUSUSER = (SELECT UserID from Deleted)If @NEWUSER <> @PREVIOUSUSERINSERT INTO ProjectAllocationLog (ProjectID, UserID, Date) VALUES (@PROJECTID, @NEWUSER, GETDATE())GoI would appreciate any comments |
|
Kristen
Test
22859 Posts |
Posted - 2007-10-23 : 02:27:39
|
You need to write your trigger assuming that more than one row will have been changed. its a common misconception that the trigger is called for each ROW changed - actually its called one for each statement, so that may result in multiple rows being changedINSERT INTO ProjectAllocationLog (ProjectID, UserID, Date) SELECT I.projected, I.UserID, D.UserID, GetDate()FROM inserted AS I JOIN deleted as D ON D.Projectid = I.Projectid What about a trigger on Delete?See also: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=55210&SearchTerms=Triggers,Trigger,audit%20changesKristen |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-10-23 : 02:33:30
|
Add a WHERE to Kristens suggestion to make it compatible with your original intent.WHERE i.UserID <> d.UserID E 12°55'05.25"N 56°04'39.16" |
 |
|
Kristen
Test
22859 Posts |
Posted - 2007-10-23 : 04:27:29
|
Missed that, thanks Peso |
 |
|
|
|
|
|
|