1

对于 Postgresql——最终是 Sybase ADS——我有可以使用自制触发器复制的表。触发器有一个函数应该记录 INSERT UPDATE DELETE 更改的信息,其中包括 I/U/D 操作和更改的行的 ID。我正在使用带有名字列和自动递增 ID 的测试表来测试双向复制。

如果我对 NAME 表进行插入,例如添加 autoID 为“1”的“JOHN”,我是否能够将该 ID 值甚至可能“JOHN”插入到日志表中?我正在查看 OLD.ID 或 NEW.ID 选项,但我不知道它是否可以这样工作。我的触发器/功能代码是:

    CREATE OR REPLACE FUNCTION Insert() RETURNS TRIGGER AS $ReplInsert$
    BEGIN
        IF (TG_OP = 'DELETE') THEN
            INSERT INTO "log" ("Operation","ID","NAME")
    VALUES ('DELETE', OLD.ID, OLD.NAME);
            RETURN OLD;
        ELSIF (TG_OP = 'UPDATE') THEN
            INSERT INTO "log" ("Operation","ID","NAME")
    VALUES ('UPDATE', NEW.ID ,NEW.NAME);
            RETURN NEW;
        ELSIF (TG_OP = 'INSERT') THEN
            INSERT INTO "log" ("Operation","ID","NAME")
    VALUES ('UPDATE', NEW.ID , NEW.NAME);
            RETURN NEW;
        END IF;
        RETURN NULL; 
    END;
$ReplInsert$ LANGUAGE plpgsql;

CREATE TRIGGER logTrg
AFTER INSERT OR UPDATE OR DELETE ON "FIRST_NAME"
    FOR EACH ROW EXECUTE PROCEDURE Insert();

这最终是为了使用触发器进行双向复制。感谢您的任何考虑或指导。我会根据需要进行编辑。

4

1 回答 1

2

我能够通过在触发器中将 AFTER 更改为 BEFORE 来解决这个问题,我起初认为这不起作用,或者:

    CREATE OR REPLACE FUNCTION Insert() RETURNS TRIGGER AS $ReplInsert$
    BEGIN
        IF (TG_OP = 'DELETE') THEN
            INSERT INTO "log" ("Operation","ID","NAME")
    VALUES ('DELETE', OLD.ID, OLD.NAME);
            RETURN OLD;
        ELSIF (TG_OP = 'UPDATE') THEN
            INSERT INTO "log" ("Operation","ID","NAME")
    VALUES ('UPDATE', NEW.ID ,NEW.NAME);
            RETURN NEW;
        ELSIF (TG_OP = 'INSERT') THEN
            INSERT INTO "log" ("Operation","ID","NAME")
    VALUES ('UPDATE', NEW.ID , NEW.NAME);
            RETURN NEW;
        END IF;
        RETURN NULL; 
    END;
$ReplInsert$ LANGUAGE plpgsql;

CREATE TRIGGER logTrg
BEFORE INSERT OR UPDATE OR DELETE ON "FIRST_NAME"
    FOR EACH ROW EXECUTE PROCEDURE Insert();
于 2019-02-09T08:21:05.680 回答