Using an SQL Trigger Statement to move or duplicate all data of a specific tuple into and audit table

StackOverflow https://stackoverflow.com/questions/17008215

Question

create table branch_audit 
    (br_branchno varchar(4),
     br_branchname varchar(20),
     br_street varchar(40) not null unique,
     br_city varchar(20),
     br_state varchar(2),
     br_zipcode varchar(5),
     br_phone varchar(10),
     br_fax varchar(10),
     br_per_mgt_fee decimal(5,2),
     br_email varchar(25),

     constraint br_primarykey primary key (br_branchno));

The above line creates the audit table with the same schema as the "branch" table so that it can capture all the old data that has been deleted

This is the trigger statement, very basic form and I was wondering if there was a way of preserving its simplicity:

CREATE TRIGGER trigger_deleteon
AFTER DELETE 
ON branch
FOR EACH ROW
INSERT INTO branch_audit VALUES(select * from branch);

DELETE FROM Branch WHERE CL_CLIENTNO = 'B001';

I'm going to try my best to explain here. So I would like the code to take the deleted value after the trigger has been activated and then take the tuple(row) that has been deleted and store it in an Audit table I have created in order to track modifications to the DB.

The underlined statement above is the statement that mus be changed to capture just the deleted tuple, currently it captures every tuple instead of just the one updated.

Was it helpful?

Solution

You can access the values of the deleted row through the OLD keyword in a MySQL trigger. Something like the following should work, where ... is to be replaced with all the other attributes.

CREATE TRIGGER trigger_deletion
    BEFORE DELETE ON branch
    FOR EACH ROW
    BEGIN 
        INSERT INTO branch_audit VALUES(OLD.br_branchno, 
            OLD.br_branchname, OLD.br_street, ...);
    END;

OTHER TIPS

You can use BEFORE DELETE trigger instead of AFTER DELETE in a following manner

CREATE TRIGGER trigger_deleteon
BEFORE DELETE ON branch
FOR EACH ROW
    INSERT INTO branch_audit 
    SELECT * 
      FROM branch
     WHERE br_branchno = OLD.br_branchno; 

Here is SQLFiddle demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top