Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

postgresql - Returning from a function with OUT parameter

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It would work like this:

CREATE OR REPLACE FUNCTION name_function(param_1 varchar
                                   , OUT param_2 bigint)
  LANGUAGE plpgsql AS
$func$
BEGIN
    INSERT INTO table (collumn_seq, param_1)  -- "param_1" also the column name?
    VALUES (DEFAULT, param_1)
    RETURNING collumn_seq
    INTO param2;
END
$func$;

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

The simple case can be covered with a plain SQL function.
And you can omit the target column that shall get its DEFAULT value.
And you can just as well use a RETURNS clause in this case:

CREATE OR REPLACE FUNCTION name_function(param_1 varchar)
  RETURNS bigint
  LANGUAGE sql AS
$func$
INSERT INTO table (param_1)  -- "param_1" also the column name?
VALUES (param_1)
RETURNING collumn_seq;
$func$;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...