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:
  1. -- ###### STEP 1 - CREATING TEST TABLES AND DATA #####   
  2.     -- Create a test table   
  3.     CREATE TABLE TABLE1 (ID int, VALUE varchar(50))   
  4.   
  5.     -- Create a test audit table   
  6.     CREATE TABLE TABLEAUDIT (ID int, OLDVALUE varchar(50), DateChanged datetime)   
  7.   
  8.     -- Populate the temp table with some test values   
  9.     INSERT TABLE1 VALUES (1, 'Test1')   
  10.     INSERT TABLE1 VALUES (2, 'Test3')   
  11.     INSERT TABLE1 VALUES (3, 'Test3')   
  12.   
  13.     -- Get all the records from the Temp Table   
  14.     SELECT * FROM TABLE1   

The trigger:
  1. -- ###### STEP 2 - CREATING THE TRIGGER #####   
  2.   
  3.     -- Create the trigger to insert an audit record   
  4.     CREATE TRIGGER tgrInsert   
  5.     ON TABLE1   
  6.     FOR UPDATE   
  7.     AS   
  8.     BEGIN   
  9.         -- Get the values that were updated   
  10.         DECLARE @ID int   
  11.         DECLARE @OLDVALUE varchar(50)   
  12.         SELECT @ID = Inserted.ID, @OLDVALUE = Inserted.Value FROM INSERTED   
  13.         -- Insert the values into the temp table   
  14.         INSERT TABLEAUDIT VALUES (@ID, @OLDVALUE, GetDate())   
  15.     END    

The results:
  1. -- ###### STEP 3 - SHOWING WHAT HAPPENS WHEN AN INSERT OCCURS #####   
  2.   
  3.     --update the temp table so the trigger fires   
  4.     UPDATE TABLE1 SET Value = 'Changed' WHERE ID = 3  
  5.   
  6.     -- Select the records from the temp and audit tables   
  7.     SELECT * FROM TABLE1   
  8.     SELECT * FROM TABLEAUDIT
posted @ 2011-01-24 13:20  Green.Lee  阅读(218)  评论(0编辑  收藏  举报