2

是否可以取消用户定义函数中的先前操作?

例如:

CREATE OR REPLACE FUNCTION transact_test () RETURNS BOOLEAN
AS $$
    BEGIN

        UPDATE table1 SET ...

        UPDATE table2 SET ...

        IF some_condition THEN
            --Here is  possible to cancel  all above operations?
            RETURN FALSE; 
        END IF;

        RETURN TRUE;
    END;
$$
LANGUAGE plpgsql;
4

1 回答 1

3

到目前为止,这两个答案都不正确。
如果您尝试启动事务或SAVEPOINT在 plpgsql 函数中使用 a ,则会收到如下错误消息:

ERROR:  cannot begin/end transactions in PL/pgSQL
HINT:  Use a BEGIN block with an EXCEPTION clause instead.
CONTEXT:  PL/pgSQL function "f_savepoint" line 6 at SQL statement

如果你尝试一个SAVEPOINT简单的 SQL 函数:

ERROR:  SAVEPOINT is not allowed in a SQL function
CONTEXT:  SQL function "f_savepoint2" during startup

如错误消息所示,请改用plpgsql 函数内的BEGIN块。您的演示可能如下所示:

CREATE OR REPLACE FUNCTION transact_test(boolean)
  RETURNS boolean AS
$func$
BEGIN -- start a nested BEGIN block
    UPDATE t SET i = i+1 WHERE i = 1;
    UPDATE t SET i = i+1 WHERE i = 3;
    IF $1 THEN
        RAISE EXCEPTION 'foo';  -- cancels all of the above
    END IF;

    RETURN TRUE;

EXCEPTION WHEN OTHERS THEN
    RETURN FALSE; 
    -- do nothing
END
$func$ LANGUAGE plpgsql;

-> SQLfiddle展示了这一切。

于 2013-05-22T22:31:15.530 回答