views:

31

answers:

3

I have a table and want to insert the current values of records that are being updated or deleted.

I tried to create a trigger on before update and on before delete but SQL Server 2005 doesn't like the before word.

How do I get this to work?

I want the trigger to take the current record and copy it to a history table that is a mirror of the base table with the two added fields of dateBackedUp (that takes a getDate()) and a field called action (that takes the action 'updated' or deleted')

please help

A: 

You don't need to use a before keyword. You can create a trigger as normal and then select from the deleted table which gets created when a trigger is..er...triggered.

eg

create trigger Audit
on tblCustomers
after update, delete

insert into tblAudit
select * from deleted;

(untested as I don't have a SQL Server here, but if doesn't work then the BOL entry for Create Trigger should tell you about the deleted table)

Paul Spangle
A: 
create TRIGGER [update_Project] ON Project
FOR UPDATE
AS
INSERT project_history 
SELECT * FROM deleted

using the deleted table works as it gives me the data that will be updated. the inserted table provides the new values... not the ones i want to log.

kacalapy
If you post code or XML, **please** highlight those lines in the text editor and click on the "code" button (101 010) on the editor toolbar to nicely format and syntax highlight it! Plus: you should **update** your original question by editing it, rather than adding a "dummy" answer yourself......
marc_s
+1  A: 

SQL Server doesn't have a concept of BEFORE INSERT or BEFORE DELETE. These kind of audit operations really don't need to be executed before the action, most of the time - so just use the AFTER INSERT and AFTER UPDATE triggers that you already have.

using the deleted table works as it gives me the data that will be updated. the inserted table provides the new values... not the ones i want to log.

When you do an AFTER UPDATE trigger, the Inserted pseudo-table contains the new values - and the Deleted table contains the old values. So for the AFTER UPDATE trigger, you can access both pseudo tables and get both the old and the new values.

The AFTER INSERT trigger only has access to Inserted pseudo table which contains the values that were inserted.

The AFTER DELETE trigger only has access to the Deleted pseudo table which contains the values of the rows that were deleted.

marc_s