如何在postgresql中为触发器插入自动增量值?

时间:2015-04-23 14:17:48

标签: sql postgresql triggers

这是来自plpgsql -

的触发器
CREATE TABLE emp (
    empname           text NOT NULL,
    salary            integer
);

CREATE TABLE emp_audit(
    operation         char(1)   NOT NULL,
    stamp             timestamp NOT NULL,
    userid            text      NOT NULL,
    empname           text      NOT NULL,
    salary integer
);

CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
    BEGIN
        --
        -- Create a row in emp_audit to reflect the operation performed on emp,
        -- make use of the special variable TG_OP to work out the operation.
        --
        IF (TG_OP = 'DELETE') THEN
            INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
            RETURN OLD;
        ELSIF (TG_OP = 'UPDATE') THEN
            INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
            RETURN NEW;
        ELSIF (TG_OP = 'INSERT') THEN
            INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
            RETURN NEW;
        END IF;
        RETURN NULL; -- result is ignored since this is an AFTER trigger
    END;
$emp_audit$ LANGUAGE plpgsql;

CREATE TRIGGER emp_audit
AFTER INSERT OR UPDATE OR DELETE ON emp
    FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();

现在我想在emp_audit表格中添加一个列,这是一个主键,比如emp_audit_id - 那么现在应该在上面的SELECT查询中出现什么,以便它也可以处理PRIMARY KEY emp_audit_id

1 个答案:

答案 0 :(得分:0)

由于您不想在INSERT语句中写出字段列表(其他读者:请参阅下面的评论),因此您需要使用常规integer作为PRIMARY KEY和手动创建序列。

首先改变emp_audit表定义:

ALTER TABLE emp_audit ADD COLUMN emp_audit_id integer PRIMARY KEY

创建序列:

CREATE SEQUENCE seq_empaudit_pk;

INSERT语句中,添加序列中的下一个值:

IF (TG_OP = 'DELETE') THEN
    INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*, nextval(seq_empaudit_pk);
    RETURN OLD;
ELSIF (TG_OP = 'UPDATE') THEN
    INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*, nextval(seq_empaudit_pk);
    RETURN NEW;
ELSIF (TG_OP = 'INSERT') THEN
    INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*, nextval(seq_empaudit_pk);
    RETURN NEW;
END IF;

确保在更改表格后验证字段的顺序,并按照该顺序列出SELECT查询中的字段。