将DB2触发器重写为PostgreSQL触发器

时间:2018-10-03 11:11:06

标签: postgresql db2 database-trigger

我正在尝试将以下触发器从DB2迁移到PostgreSQL:

DB2触发器:

CREATE TRIGGER trig1
AFTER UPDATE ON table1
REFERENCING OLD AS O NEW AS N
FOR EACH ROW MODE DB2SQL
WHEN (N.field1 <> O.field1)
BEGIN ATOMIC
INSERT INTO table1(field1, field2)
VALUES (N.field1, O.field2);
END #

我将触发器改写为PostgreSQL标准(不确定是否正确):

PostgreSQL触发器:

CREATE OR REPLACE FUNCTION create_table1_history() RETURNS TRIGGER AS $table1_history$
    BEGIN
        IF (TG_OP = 'UPDATE') THEN
            INSERT INTO table1 
                SELECT 
                NEW.field1, OLD.field2;
            RETURN OLD;
        END IF;
        RETURN NULL;
    END;
$table1_history$ LANGUAGE plpgsql;


CREATE TRIGGER trig1
AFTER UPDATE ON table1
    FOR EACH ROW EXECUTE PROCEDURE create_table1_history();

现在我不确定如何在PostgreSQL触发器中添加以下条件?

WHEN (N.field1 <> O.field1)

2 个答案:

答案 0 :(得分:2)

您可以在触发触发器时添加条件:

type Config = {
    a?: number
    b?: string
}

function g<T extends Config>(x: T & Config): T {
    return x
}
let justA = g({ a: 0 });// of type { a: number }
g ({ /* Ctrl Space here suggets a and b  */})

如果该列可以包含NULL值,则最好使用

CREATE TRIGGER trig1
AFTER UPDATE ON table1
    FOR EACH ROW 
    WHEN (new.field1 <> old.field1)
    EXECUTE PROCEDURE create_table1_history();

触发器函数可以简化,并且您不需要检查TG_OP,因为触发器本身定义为仅在UPDATE上触发

    WHEN (new.field1 IS DISTINCT FROM old.field1)

答案 1 :(得分:0)

在以下情况下只需添加另一个即可:

https://docs.google.com/gview?embedded=true&url=https://www.unm.edu/~unmvclib/powerpoint/pptexamples.ppt