Trigger in postgre SQL (instance application, how to back up and update the previous differential data)

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.