views:

193

answers:

1

Is there a way to actually get the column name that was updated in order to use it in a trigger?

Basically I'm trying to have an audit trail whenever a user inserts or updates a table (in this case it has to do with a Contact table)

CREATE TRIGGER `after_update_contact`
    AFTER UPDATE ON `contact` FOR EACH ROW
    BEGIN
        INSERT INTO user_audit (id_user, even_date, table_name, record_id, field_name, old_value, new_value)
        VALUES (NEW.updatedby, NEW.lastUpdate, 'contact', NEW.id_contact, [...])
    END

How can I get the name of the column that's been updated and from that get the OLD and NEW values of that column. If multiple columns have been updated in a row or even multiple rows would it be possible to have an audit for each update?

+2  A: 

Just use OLD.colname <> NEW.colname to check if these are different. Triggers are a bit limited in their use in MySQL, too bad.

Frank Heikens
Unless I misunderstood what you meant I'm not quite sure how that helps me, I don't know in advance what column is being updated so I can't hardcode it in the trigger. I need to find out what column has been updated and insert it's name in the audit table.
Serge
So you have to check all columns. As I told you, triggers are pretty limited in MySQL.
Frank Heikens
I was afraid of that... So if my table has 5 columns I'll need to use if statements as well as an INSERT for each in order to audit every updated column?
Serge
Excellent answer!
Sana