我想在使用postgresql触发器将行插入实际表时,从实际表(父和子)中将行插入历史表中

时间:2016-11-02 06:25:25

标签: postgresql triggers

例如:

考虑我原来的表格是:

    CREATE TABLE employees(
    id  serial primary key,
    first_name varchar(40) NOT NULL,
    last_name varchar(40) NOT NULL
    );



    CREATE TABLE employees_detail
    (
    eid integer NOT NULL,
    id integer,
    first_name character varying(40),
    last_name character varying(40),
    CONSTRAINT employees_detail_pkey PRIMARY KEY (eid),
    CONSTRAINT employees_detail_id_fkey FOREIGN KEY (id)
    REFERENCES employees (id) MATCH SIMPLE
    ON UPDATE NO ACTION ON DELETE NO ACTION
    )

上表有外键关系。因此,当我在两个表中插入一行时,同时我想将它们插入到历史表中。

考虑历史记录表:

    CREATE TABLE employee_audits (
    id  serial primary key,
    employee_id int4 NOT NULL,
    last_name varchar(40) NOT NULL,
    changed_on timestamp(6) NOT NULL
    )




    CREATE TABLE employee_audits_detail
    (
    eid integer NOT NULL,
    id integer,
    last_name character varying(40),
    changed_on timestamp(6) NOT NULL,
    CONSTRAINT employee_audits_detail_pkey PRIMARY KEY (eid),
    CONSTRAINT employee_audits_detail_fkey FOREIGN KEY (id)
    REFERENCES employee_audits (id) MATCH SIMPLE
    ON UPDATE NO ACTION ON DELETE NO ACTION
    )

我创建了以下触发器,以便将原始父表(员工)插入历史记录父表( employee_audits )。我的触发器如下:

    CREATE OR REPLACE FUNCTION log_last_name_changes()
    RETURNS trigger AS
    $BODY$
    BEGIN
     IF NEW.last_name <> OLD.last_name THEN
     INSERT INTO employee_audits(employee_id,last_name,changed_on)
     VALUES(OLD.id,OLD.last_name,now());
     END IF;
      RETURN NEW;
    END;
    $BODY$
    LANGUAGE plpgsql

    CREATE TRIGGER last_name_changes
    BEFORE UPDATE 
    ON employees
    FOR EACH ROW
    EXECUTE PROCEDURE log_last_name_changes();

我希望将原始子表行插入历史子表中。

0 个答案:

没有答案