There are two tables: user and diff_user_list.
When the user table is added, deleted, modified, and queried, or a field changes, the field is inserted to the diff_user_list table.
The following code stores old records in the diff_user_list table when the field "name" in the User table is updated.
You can also write the code for backing up the previous data when inserting data to delete the data.
create or replace function make_diff_user_list() returns trigger as$body$ declare curtime timestamp; begin curtime := `now`; IF(TG_OP = 'UPDARE' ) THEN IF (OLD.user_name != NEW.user_name ) THEN INSERT INTO diff_user_list (user_id, user_name, update_time, operate_flg) VALUES ( OLD.user_id, OLD.user_name, curtime, `1` ); RETURN NULL; END IF; END IF; RETURN NULL; EXCEPTION WHEN OTHERS THEN RETURN NULL; end;$body$ language 'plpgsql' volatile cost 100;
Description
The above code is a stored procedure (Procedure)
There is $ body $, which can be something other than body, such as diff_user_list.
The following code creates a trigger and is associated with the above stored procedure.
create trigger diff_user_listafter insert or update or delete ON userfor each row execute procedure make_diff_user_list();
Note:
========================================================== ========
If an error is reported
Language "plpgsql" dose not exist
Execute the following statement:
Create language plpgsql