Returning from a function with OUT parameter

2019-01-20 11:51发布

I have an error, but I don't know what the problem is.

I want execute a function and return a value from a column filled in by the column default, a sequence - the equivalent of currval(sequence).

I use:
PostgreSQL 9.0
pgAdmin III

CREATE OR REPLACE FUNCTION name_function(in param_1 character varying
                                      , out param_2 bigint)
  AS
$$
BEGIN
    INSERT INTO table (collumn_seq,param_1) VALUES (DEFAULT,param_1)
    returning collumn_seq;
--where:collumn_seq reference a collumn serial..
END;
$$
  LANGUAGE plpgsql VOLATILE;

I can create the function without error but when trying to execute, the following error is returned:

SELECT name_function('GHGHGH');

ERROR: The query has no destination for result data

1条回答
萌系小妹纸
2楼-- · 2019-01-20 12:25

It would work like this:

CREATE OR REPLACE FUNCTION name_function(param_1 character varying
                                   , OUT param_2 bigint) AS
$func$
BEGIN
    INSERT INTO table (collumn_seq, param_1)
    VALUES (DEFAULT, param_1)
    RETURNING collumn_seq
    INTO param2;
END
$func$ LANGUAGE plpgsql;

Normally, you would add a RETURN statement, but with OUT parameters, this is optional.
Refer to the manual for more details:

查看更多
登录 后发表回答