对于Postgresql(最终是Sybase ADS),我有一些使用自制触发器进行复制的表。触发器具有应记录有关INSERT UPDATE DELETE更改的信息的功能,该更改包括I / U / D操作和更改的行的ID。我正在使用带有名字列和自动递增ID的测试表来测试双向复制。
如果我在NAME表中进行插入(例如添加自动ID为“ 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();
这最终将使用触发器进行双向复制。感谢您的任何考虑或指导。我将根据需要进行编辑。
答案 0 :(得分:0)
我能够通过将触发器中的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();