I’m trying to create a database trigger in SQL Server 2008 for a tblCustomer table. I need it to add a new row into the tblChanges table every time there is an insert, update, or delete within the tblCustomer table.
Specifically, I need it to insert the CustomerId (PK) that was changed, the dateTime that it the changed occurred, and the type of change (insert, update, delete).
I’ve got something along these lines so far but can’t figure out the rest:
CREATE TRIGGER change_trigger
AFTER INSERT OR UPDATE OR DELETE
ON tblCustomer
DECLARE log_action varchar(30)
BEGIN
IF INSERTING THEN
log_action := 'I';
ELSEIF UPDATING THEN
log_action := 'U';
ELSEIF DELETEING THEN
log_action := 'D';
ELSE
DBMS_OUTPUT.PUT_LINE('undefined');
END IF;
INSERT INTO tblChanges(ChanedPK, ChangedTime, ChangedType)
VALUES ...
I’m unsure if any of the above SQL is correct as I haven’t tried running it yet and my knowledge of SQL is limited. Any help completing the code and correcting errors would be appreciated.
Try something along these lines:
Maybe you should read up un T-SQL and DML triggers in SQL Server first. MSDN and many other sites provide excellent examples on how to go about things.