PostgreSQL错误代码,设置自定义错误代码

时间:2018-06-08 14:23:34

标签: postgresql error-handling triggers

我正在将Oracle触发器转换为Postgres;到目前为止,我已将其翻译成postgres

DROP TRIGGER IF EXISTS trg_test_biud ON mytable CASCADE;
CREATE OR REPLACE FUNCTION trigger_fct_trg_test_biud() RETURNS trigger AS $BODY$
DECLARE
    id_ double precision := NULL;
    hour_ varchar(10) := NULL;
BEGIN

    /* INSERT */
    IF TG_OP = 'INSERT' THEN
        BEGIN
            select nextval('myschema.id_audit_mytable_seq') into id_;
            SELECT  TO_CHAR(current_timestamp, 'HH24:MI:SS') INTO hour_;
            INSERT INTO myschema.audit_mytable(id, id_mytable, user_name, event, myhour, hour, geometry)
                VALUES (id_, NEW.code, NEW.user_name, 'INSERT', LOCALTIMESTAMP, hour_, NEW.GEOMETRY);
            RETURN NEW;
            EXCEPTION
            WHEN OTHERS THEN
                RAISE EXCEPTION '%', 'Error when insert into audit_mytable: ' || sqlerrm USING ERRCODE = '-20000';

        END;

    END IF;

END
$BODY$
 LANGUAGE 'plpgsql';

CREATE TRIGGER trg_test_biud
    BEFORE INSERT OR UPDATE OR DELETE ON myschema.mytable FOR EACH ROW
    EXECUTE PROCEDURE trigger_fct_trg_test_biud();

引发异常时,我收到此错误:

ERROR: unrecognized exception condition «-20000»
SQL state: 42704

这是否与Oracle中“自定义错误代码”为负数的事实有关? postgres不承认这个?我查看了此页面,但它没有说明负数:https://www.postgresql.org/docs/current/static/errcodes-appendix.html

1 个答案:

答案 0 :(得分:2)

Oracle编号-20000不是SQLSTATE,而是专有错误代码。

您必须指定文档附录A中定义的5个字符的SQLSTATE之一。