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 |
|
sardinka
Posting Yak Master
142 Posts |
Posted - 2004-08-11 : 10:00:26
|
| I've created a trigger for update. However it is not working correct.I would like to get the data before update and after update if more then 1 row updated. How do I do this?CREATE TRIGGER dbo.mstr_Log ON mstrFOR UPDATEASBEGIN -- Audit OLD record. Insert Into mstr_Log (user,Insert_date) select id,'Old',getDate() from table -- Audit NEW record. Insert Into mstr_Log (user,Insert_date) select id,'New',getDate()from tableEND |
|
|
mwjdavidson
Aged Yak Warrior
735 Posts |
Posted - 2004-08-11 : 10:32:22
|
| There's a fair bit of stuff on this topic if you search for something like 'Audit Trigger'.However, a lot of links seem to be down at the moment, so here's an example:--Create tableCREATE TABLE dbo.People( PersonID INT IDENTITY(1, 1), FirstName NVARCHAR(50), LastName NVARCHAR(50))--Populate tableINSERT INTO dbo.People( FirstName, LastName)VALUES( N'Mark', N'Davidson')--Create log tableCREATE TABLE dbo.People_Log( PersonID INT, FirstName NVARCHAR(50), LastName NVARCHAR(50), State VARCHAR(6), DateOfChange DATETIME)--TriggerCREATE TRIGGER TR_U_PeopleON dbo.PeopleFOR UPDATEASINSERT INTO dbo.People_LogSELECT d.PersonID, d.FirstName, d.LastName, 'Before' AS State, CURRENT_TIMESTAMP AS DateOfChangeFROM deleted AS dUNIONSELECT i.PersonID, i.FirstName, i.LastName, 'After', CURRENT_TIMESTAMPFROM inserted AS iORDER BY d.PersonID, State--Update rowUPDATE dbo.People SET FirstName = 'James'WHERE dbo.People.PersonID = 1--Select from logSELECT pl.PersonID , pl.FirstName , pl.LastName , pl.State , pl.DateOfChange FROM dbo.People_Log AS plMark |
 |
|
|
Kristen
Test
22859 Posts |
Posted - 2004-08-11 : 12:59:07
|
| CREATE TRIGGER dbo.mstr_Log ON mstrFOR UPDATEASBEGIN-- Audit OLD record.Insert Into mstr_Log(user,Insert_date)select id,'Old',getDate() from deleted-- Audit NEW record.Insert Into mstr_Log(user,Insert_date)select id,'New',getDate()from insertedENDIf you only want to log changes when MORE THAN one row is updated, then put the two INSERTs in:IF (SELECT COUNT(*) FROM inserted) > 1 THENBEGIN... inserts hereENDNote also that you are msising a column nameInsert Into mstr_Log(user, ChangeType, Insert_date)Kristen |
 |
|
|
|
|
|
|
|