I want to create a history table to track field changes in multiple tables in DB2.
I know that a story is usually executed by copying the entire structure of the table and giving it a suffix name (for example, user → user_history). Then you can use a fairly simple trigger to copy the old record to the history table in UPDATE.
However, for my application this will use too much space. It seems to me that it is not recommended (at least to me) to copy the entire record to another table every time a field is changed. Therefore, I thought that I could have a common history table that would track changes to individual fields:
CREATE TABLE history ( history_id LONG GENERATED ALWAYS AS IDENTITY, record_id INTEGER NOT NULL, table_name VARCHAR(32) NOT NULL, field_name VARCHAR(64) NOT NULL, field_value VARCHAR(1024), change_time TIMESTAMP, PRIMARY KEY (history_id) );
OK, so every table that I want to track has one, automatically generated id field as the primary key, which will be placed in the "record_id" field. The maximum VARCHAR size in tables is 1024. Obviously, if a field other than VARCHAR is changed, it must be converted to VARCHAR before inserting the record into the history table.
Now this can be a completely inhibited way to do something (hey, let me know why, if so), but I think this is a good way to track changes that you rarely need to cut and need to be stored for a considerable amount of time.
In any case, I need help writing a trigger to add entries to the update history table. Let, for example, take a hypothetical user table:
CREATE TABLE user ( user_id INTEGER GENERATED ALWAYS AS IDENTITY, username VARCHAR(32) NOT NULL, first_name VARCHAR(64) NOT NULL, last_name VARCHAR(64) NOT NULL, email_address VARCHAR(256) NOT NULL PRIMARY KEY(user_id) );
So, can someone help me with the trigger when updating the user table to insert the changes into the history table? I assume that some procedural SQL will be used to cycle through the fields in the old record, compare them with the fields in the new record, and if they do not match, then add a new record to the history table.
It would be preferable to use the same SQL query action for each table, regardless of its fields, if possible.
Thanks!