Using the INSERTED table in SQL Server 2000
Using the INSERTED table in SQL Server 2000
Summary: An example trigger that shows how to get the values from an update statement and write them out to an audit table
Test data:
The trigger:
The results:
- -- ###### STEP 1 - CREATING TEST TABLES AND DATA #####
- -- Create a test table
- CREATE TABLE TABLE1 (ID int, VALUE varchar(50))
- -- Create a test audit table
- CREATE TABLE TABLEAUDIT (ID int, OLDVALUE varchar(50), DateChanged datetime)
- -- Populate the temp table with some test values
- INSERT TABLE1 VALUES (1, 'Test1')
- INSERT TABLE1 VALUES (2, 'Test3')
- INSERT TABLE1 VALUES (3, 'Test3')
- -- Get all the records from the Temp Table
- SELECT * FROM TABLE1
The trigger:
- -- ###### STEP 2 - CREATING THE TRIGGER #####
- -- Create the trigger to insert an audit record
- CREATE TRIGGER tgrInsert
- ON TABLE1
- FOR UPDATE
- AS
- BEGIN
- -- Get the values that were updated
- DECLARE @ID int
- DECLARE @OLDVALUE varchar(50)
- SELECT @ID = Inserted.ID, @OLDVALUE = Inserted.Value FROM INSERTED
- -- Insert the values into the temp table
- INSERT TABLEAUDIT VALUES (@ID, @OLDVALUE, GetDate())
- END
The results:
- -- ###### STEP 3 - SHOWING WHAT HAPPENS WHEN AN INSERT OCCURS #####
- --update the temp table so the trigger fires
- UPDATE TABLE1 SET Value = 'Changed' WHERE ID = 3
- -- Select the records from the temp and audit tables
- SELECT * FROM TABLE1
- SELECT * FROM TABLEAUDIT